垂直水平居中的方案有很多,有时候容易搞混。
其实细分下来主要有两种场景:元素宽高未知的场景、元素宽高已知的场景。针对这两种情况,后文分别列出集中主流的垂直水平居中方案。
元素宽高未知的场景
table 实现垂直水平居中【推荐】
table垂直水平居中方案,是万金油方案,适用性极强,也没有兼容性问题;缺陷是会增加冗余的HTML结构。
<div class="vertical center">
<div class="box-container">
<span class="box">haha</span>
</div>
</div>
.vertical {
width: 100%;
height: 100%;
display: table;
}
.vertical.center {
text-align: center;
}
.vertical .box-container {
display: table-cell;
vertical-align: middle;
}
.vertical .box-container .box {
vertical-align: middle;
}
transform 实现垂直水平居中【推荐】
transform垂直水平居中方案,同样也是万金油方案,尤其适合移动端;缺陷是只支持IE9及以上的浏览器。
<span class="box">haha</span>
// transform是以自身宽高为基准计算的
.box {
position: relative;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
flexbox 实现垂直水平居中
移动端可以使用;缺陷是只支持IE10及以上的浏览器。
<div class="box-container">
<span class="box"></span>
</div>
// transform是以自身宽高为基准计算的
.box-container {
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
display: flex;
justify-content: center;
align-items: center;
}
元素宽高已知的场景
绝对定位 实现垂直水平居中
比较常用的方案,需要已知宽高。
<div class="box-container">
<span class="box"></span>
</div>
.box-container{
position: relative;
}
.box-container .box {
width: 600px;
height: 400px;
position: absolute;
left: 50%;
top: 50%;
margin-top: -200px; /* 高度的一半 */
margin-left: -300px; /* 宽度的一半 */
}
margin:auto 实现垂直水平居中
特别适合自身有宽高的元素,比如图片等;但是对于其他元素,仍然需要显式设置宽高。
// 图片等自身带宽高的元素,直接 margin: auto; 即可
<div class="box-container">
<img class="box" />
</div>
.box-container{
position: relative;
}
.img {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
// 其他场景需要显式设置宽高
<div class="box-container">
<span class="box"></span>
</div>
.box-container{
position: relative;
}
.box {
width: 100px;
height: 100px;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
}
网友评论