行內元素水平居中
只需要給父元素設定text-align:center;即可,
<div>
<span>行內水平居中</span>
</div>
div{
border:1px solid red;
text-align:center;
}

塊級元素水平居中
定寬
margin: 0 auto;
塊級元素的width一定時,只需要給需要居中的塊級元素設定margin: 0 auto;即可,
<div>定寬塊級元素水平居中</div>
div {
width: 200px;
border: 1px solid red;
margin: 0 auto;
}
position + margin-left
使用絕對定位,然后設定left: 50%;以及margin-left設定為負的寬度的一半,
<div>定寬</div>
div {
border: 1px solid red;
position: absolute;
width: 80px;
left: 50%;
margin-left: -40px;
}
position + left + right + margin
使用絕對定位,然后給left、right都設定為0,然后再設定margin:0 auto;即可,
<div>定寬</div>
div {
border: 1px solid red;
position: absolute;
width: 80px;
left:0;
right:0;
margin:0 auto;
}
不定寬
table + margin
當寬度不固定時,給居中的元素設定display: table;和margin: 0 auto;即可,
<div>不定寬塊級元素水平居中</div>
div {
border: 1px solid red;
margin: 0 auto;
display: table;
}
inline-block + text-align
當有一個或多個塊級元素時,給父元素設定text-align: center;,然后給子元素設定display: inline-block;即可,
<div class="father">
<div class="son">son1</div>
<div class="son">son2</div>
</div>
.father {
border: 1px solid green;
text-align: center;
}
.son {
border: 1px solid red;
display: inline-block;
}
flex
只需要給父元素設定display: flex;和justify-content: center;即可,
<div class="father">
<div class="son">son1</div>
<div class="son">son2</div>
</div>
.father {
border: 1px solid green;
display: flex;
justify-content: center;
}
position + transform
<div>transform實作</div>
div {
border: 1px solid red;
position: absolute;
left: 50%;
transform: translateX(-50%);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/7081.html
標籤:Html/Css
上一篇:CSS基礎面試題查漏補缺
