水平垂直居中有好多种实现方式,主要就分为两类:不定宽高
和定宽高
,以在body下插入一个div为例:
定宽高 使用定位+margin
element.style {position: absolute;left: 50%;top: 50%;margin-left: -250px;margin-top: -250px;width: 500px;height: 500px;background: yellow;z-index: 1;}
使用定位+transfrom
element.style {position: absolute;left: 50%;top: 50%;width: 500px;height: 500px;background: yellow;z-index: 1;transform: translate3d(-50%,-50%,0);}
table-cell 方式
div.parent-box {display: table;width: 100%;}div.parent {display: table-cell;height: 200px;width: 200px;background-color: orange;text-align: center;vertical-align: middle;}div.child {display: inline-block;width: 100px;height: 100px;background-color: blue;}
<div class="parent-fix"><div class="parent"><div class="child">DEMO</div></div></div>
table-cell 是不支持设置 width: 100%; 想让 .parent 和 其容器宽度一致最好设置一个 dispaly: table; 父容器。calc方式
.parent {border: 1px solid;width: 1000px;height: 1000px;}.child {position: relative;border: 1px solid;width: 100px;height: 100px;top: calc(50% - 50px);left: calc(50% - 50px);}
不定宽高:不定宽高的方法基本都适用于定宽高的情况,这里把div的宽高按照内容展开,使用定位+transform同样是适用的
div.parent {position: reletive;}element.style {position: absolute;left: 50%;top: 50%;background: yellow;z-index: 1;transform: translate3d(-50%,-50%,0);}
flex、grid方法:
div.parent{display:flex;}div.child{margin:auto;}
// 子元素自动垂直水平居中div.parent {display: flex;justify-content: center;align-items: center;}
或者
div.parent{display:flex;}div.child{margin:auto;}
static 方法
div.parent {font-size: 0;text-align: center;&::before {content: "";display: inline-block;width: 0;height: 100%;vertical-align: middle;}}div.child{display: inline-block;vertical-align: middle;}
此法来自张鑫旭的《CSS世界》,原理就是:设置inline-block
和vertical-align:middle
后,里面的元素会基于中间的文字准线居中对齐(学生时代的英语本子里面写字母,都是4条线形成三个空白区域,文字的对齐就是根据这几条线的)vertical-align
更多信息可以看看张鑫旭博文; 然后,由于伪类是position:static(默认)
的,那么伪类撑开了父元素的基准线(高度是100%),使得此时文字的基准线就是整个div.parent的中心了,另外vertical-align
只影响inline
或者inline-block
的,所以div.child设置vertical-align
就能居中了。
参考资料:/question/css/52.html