元素居中
一、水平居中
text-align: center;
二、垂直居中
1.已知宽高 - 绝对定位
position:absolute; width:200px; height:100px;
top:50%; left:50%; margin-top:-50px; margin-left:100px;
top: calc(50% - 50px); left: calc(50% - 100px);
/*外边距使用 vh 为单位,因为margin的百分比值是相对于其父元素的宽度作为基准解析,因此此处使用 vh*/
transform: translateY( -50% );margin: 50vh auto 0;
2.已知宽高
vertical-align: middle;
3.未知高度 - 绝对定位
position:absolute; top:50%; left:50%;
transform: translate( -50%, -50% );
4.伪类元素 - 父元素设置伪类
.box {text-align: center;height: 500px;}
.box::before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
/* 垂直居中的元素,可以是任意宽高 */
.centered {
display: inline-block;
vertical-align: middle;
}
5. Flexbox布局 - 水平/垂直居中【不兼容IE9】
.block {display: flex; min-height: 100vh;width: 100%;}
.centered {margin: auto;}
/*或直接用flex的属性*/
.block {display: flex;justify-content: center;align-items: center;}