一般兼容性较好的垂直水平居中有三种:
1.容器内元素为内联元素或内联块元素,并且只有单行文字时
<div class="box">
<span>我是内联元素</span>
</div>
.box {
text-align:center;
height:40px;
line-height:40px;
background:red;
}
2.容器内元素时块元素,元素宽高已知
<div class="box">
<p>我是已知宽高的块元素</p>
</div>
.box {
position:relative;
height:200px;
width:200px;
background:red;
}
.box p {
position:absolute;
left:50%;
top:50%;
width:100px;
height:100px;
margin-left:-50px;
margin-top:-50px;
background:green;
}
3.容器内元素为块元素,但宽高未知
<div class="box">
<p>我是未知宽高的块元素</p>
</div>
.box p {
position:absolute;
left:0;
right:0;
top:0;
bottom:0;
margin:auto;
background:green;
}
PS:定位加translate 和 flex布局也可以实现垂直水平布局,就是兼容性不太好。 哪里有问题,欢迎您提出