html结构
<div class="parent">
<div class="child">child</div>
</div>
01 行内元素(单行文字垂直居中):设置 line-height = height
很常用,主要用于文字的排版,也可以用于图片元素居中
.parent {
height: 200px;
line-height: 200px;
border: 1px solid red;
}
02 块级元素:display: flex
优点:更灵活,也更简洁,可维护性也更强。只要不考虑IE,这个方案几乎是最优选择吧。
缺点:如果还在使用IE浏览器的话,flex布局就没那么香了。
.parent {
width: 600px;
height: 200px;
border: 1px solid red;
display: flex;
align-items: center;
justify-content: center; /*水平居中*/
}
.child {
background: blue;
}
03 块级元素:绝对定位 + margin: auto;
优点:不需要提前知道尺寸,兼容性好
缺点:这个方法曾经是我最喜欢用的一个,但是目前已经不建议使用绝对定位 absolut了,如果还在用IE开发,这个方法还是比较推荐的。
.parent {
position: relative;
height: 200px;
}
.child {
width: 80px;
height: 40px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
background: blue;
}
04 块级元素:display: table-cell
优点:也是一个比较好的实现方式,较简洁
.parent {
width: 600px;
height: 200px;
border: 1px solid red;
display: table;
}
.child {
display: table-cell;
vertical-align: middle;
}
05 块级元素:绝对定位(需要提前知道尺寸)
优点: 兼容性不错,也算是一点小技巧吧。
缺点:需要提前知道 child 的尺寸,margin-top: -(高度的一半); margin-left: -(宽度的一半); 现在已经不建议使用绝对定位 absolute,特别是在移动设备上。
.parent {
position: relative;
height: 200px;
}
.child {
width: 80px;
height: 40px;
background: blue;
position: absolute;
left: 50%;
top: 50%;
margin-top: -20px;
margin-left: -40px;
}
06 块级元素:绝对定位 + transform
优点:不需要提前知道尺寸
缺点:兼容性一般般
.parent {
position: relative;
height: 200px;
}
.child {
width: 80px;
height: 40px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
background: blue;
}
07 块级元素:padding
缺点:如果高度固定,需要提前计算尺寸(只在某些特定情况适用)。
.parent {
padding: 5% 0;
}
.child {
padding: 10% 0;
background: blue;
}
08 块级元素:伪元素
.parent {
width: 300px;
height: 300px;
border: 1px solid red;
text-align: center;
}
.child {
background: blue;
width: 100px;
height: 40px;
display: inline-block;
vertical-align: middle;
}
.parent::before {
content: '';
height: 100%;
display: inline-block;
vertical-align: middle;
}
09 块级元素:calc()
也是个不错的方法。
缺点:需要知道child的尺寸,需要计算,同样的,如果还在使用IE的小伙伴,不推荐。
.parent {
width: 300px;
height: 300px;
border: 1px solid red;
position: relative;
}
.child {
width: 100px;
height: 100px;
background: blue;
padding: -webkit-calc((100% - 100px) / 2);
padding: -moz-calc((100% - 100px) / 2);
padding: -ms-calc((100% - 100px) / 2);
padding: calc((100% - 100px) / 2);
background-clip: content-box;
}
10 块级元素:改成行内块:inline-block + vertical-align: middle;
<div class="parent">
<div class="child">child</div>
<div class="brother">brother</div>
</div>
.parent {
width: 400px;
height: 400px;
border: 1px solid red;
position: relative;
}
.child, .brother {
display: inline-block;
vertical-align: middle;
}
.child {
background: blue;
font-size: 12px;
}
.brother {
height: 400px;
font-size: 0;
}
总结
不考虑IE用02(display:flex)
需要考虑IE用03(定4边)