垂直水平居中的方案有很多添谊,有時(shí)候容易搞混痪伦。
其實(shí)細(xì)分下來主要有兩種場景:元素寬高未知的場景、元素寬高已知的場景遭贸。針對(duì)這兩種情況戈咳,后文分別列出集中主流的垂直水平居中方案。
元素寬高未知的場景
table 實(shí)現(xiàn)垂直水平居中【推薦】
table垂直水平居中方案壕吹,是萬金油方案著蛙,適用性極強(qiáng),也沒有兼容性問題算利;缺陷是會(huì)增加冗余的HTML結(jié)構(gòu)册踩。
<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 實(shí)現(xiàn)垂直水平居中【推薦】
transform垂直水平居中方案,同樣也是萬金油方案效拭,尤其適合移動(dòng)端暂吉;缺陷是只支持IE9及以上的瀏覽器。
<span class="box">haha</span>
// transform是以自身寬高為基準(zhǔn)計(jì)算的
.box {
position: relative;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
flexbox 實(shí)現(xiàn)垂直水平居中
移動(dòng)端可以使用缎患;缺陷是只支持IE10及以上的瀏覽器慕的。
<div class="box-container">
<span class="box"></span>
</div>
// transform是以自身寬高為基準(zhǔn)計(jì)算的
.box-container {
display: -webkit-flex;
display: -moz-flex;
display: -ms-flex;
display: -o-flex;
display: flex;
justify-content: center;
align-items: center;
}
元素寬高已知的場景
絕對(duì)定位 實(shí)現(xiàn)垂直水平居中
比較常用的方案,需要已知寬高挤渔。
<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 實(shí)現(xiàn)垂直水平居中
特別適合自身有寬高的元素肮街,比如圖片等;但是對(duì)于其他元素判导,仍然需要顯式設(shè)置寬高嫉父。
// 圖片等自身帶寬高的元素,直接 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;
}
// 其他場景需要顯式設(shè)置寬高
<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;
}