<div class="box"> <div class="sub size">123123</div> </div> css: .box { border: 1px solid red; width: 300px; height: 300px; } .sub{ background: green; } .sub.size{ width: 100px; height: 100px; }
一: absolute + 负margin
子元素需要定宽高,相对于父元素的宽高
.box {
position: relative;
}
.sub {
position: absolute;;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
二、absolute + margin auto
通过设置各个方向的距离都是0,再将margin设为auto,就可以在各个方向上居中了。需要子元素定宽高。
.box { position: relative; } .sub { position: absolute;; top: 0; left: 0; right: 0; bottom: 0; margin: auto; }
三、absolute + transform
不需要子元素固定宽高
.box { position: relative; } .sub { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
四、css-table
css新增的table属性,可以让我们把普通元素,变为table元素的现实效果,通过这个特性也可以实现水平垂直居中
.box { display: table-cell; text-align: center; vertical-align: middle; } .sub { display: inline-block; }
五:flex
.box { display: flex; justify-content: center; align-items: center; }