第一种
最先想到的就是使用绝对定位 + margin: auto的实现方式,这也是最靠谱的一种实现方式,兼容性还不错。为什么说它靠谱呢?因为它利用了 css 流体的特性,即页面的默认文档流是自上而下,自左向右。
HTML代码
<div class="dialog">
<div class="text"></div>
</div>
CSS代码
.dialog{
width: 500px;
height: 500px;
background-color: #cccccc;
position: relative;
}
.text{
width: 200px;
height: 200px;
background-color: #e8491d;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
第二种
已知宽度,margin 负值的方法
HTML代码
<div class="dialog">
<div class="text"></div>
</div>
CSS代码
.dialog{
width: 500px;
height: 500px;
background-color: #cccccc;
position: relative;
}
.text{
width: 200px;
height: 200px;
background-color: #e8491d;
position: absolute;
left: 50%;
top: 50%;
margin-left: -100px;
margin-top: -100px;
}
第三种
跟第一种差不多,只不过把 margin 换成了 transform 属性
HTML代码
<div class="dialog">
<div class="text"></div>
</div>
CSS代码
.dialog{
width: 500px;
height: 500px;
background-color: #cccccc;
position: relative;
}
.text{
width: 200px;
height: 200px;
background-color: #e8491d;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
第四种
flex 布局
HTML代码
<div class="dialog">
<div class="text"></div>
</div>
CSS代码
.dialog{
width: 500px;
height: 500px;
background-color: #cccccc;
display: flex;
justify-content: center;
align-items: center;
}
.text{
width: 200px;
height: 200px;
background-color: #e8491d;
}
第五种
使用 table 布局,这种不推荐使用,主要上面有那么多种方法,没必要用到这种,具体原理是给父元素设置display:table,子元素设置display:table-cell,table-cell 相当于表格中的 ,再结合vertical-align: middle即可。
HTML代码
<div class="dialog">
<div class="text">
<div class="son"></div>
</div>
</div>
CSS代码
.dialog{
width: 500px;
height: 500px;
background-color: #cccccc;
display: table;
}
.text{
background-color: #e8491d;
display: table-cell;
text-align: center;
vertical-align: middle;
}
.son{
background-color: #d0d6d9;
display: inline-block;
width: 200px;
height: 200px;
}
实现垂直居中的方法有很多,每一种都有各自的实现路径,但是兼容性却是各不相同,感兴趣的可以自己去测试下兼容。如果你有耐心从头看到这里,已经是很不错了,不过,看完可以敲一遍代码过一遍,可能记忆会来得更深刻些,希望这篇文章对你有帮助!