假設(shè)html元素為下面這樣,父容器和子容器的寬高均為不確定
<div class="parent">
<div class="child">Demo</div>
</div>
下面四種方案對其水平居中
方案一: test-align+inline-block
.parent{
text-align: center;
}
.child{
display: inline-block;
}
優(yōu)點(diǎn):兼容性好;
缺點(diǎn):text-align: center;會(huì)被child元素繼承下來,需要額外的代碼來修復(fù).
方案二 margin+table
.child{
display: table;
margin:0 auto;
}
優(yōu)點(diǎn):只對child元素進(jìn)行處理.
方案三 absolute+transform
.parent{
position: relative;
}
.child{
position: absolute;
left:50%;
transform: translateX(-50%);//參照物為自身
}
優(yōu)點(diǎn):脫離文檔流,不會(huì)對其他元素產(chǎn)生影響;缺點(diǎn):兼容性差.
方案四 flex+justify—content
.parent{
display: flex;
justify-content: center;
}
優(yōu)點(diǎn):只對parent元素進(jìn)行設(shè)置