前言
前端開發(fā)中元素居中是最常見和最經(jīng)常使用到的css技巧,不僅開發(fā)中經(jīng)常會用到,面試官出題考核基礎(chǔ)時有時候也會問道這類問題。本文主要介紹水平居中的方法。希望對你我都有幫組。
1、text-align: center
實現(xiàn)
如果父元素是塊級元素且里面包含行內(nèi)元素,則直接給父元素設(shè)置 text-align: center
, 如果父元素是行內(nèi)元素的話父元素?zé)o法設(shè)置寬高,則需要將其設(shè)為塊級元素display: block
。也對inline、inline-block、inline-table和inline-flex元素水平居中都有效。
HTML
// 父元素是塊級元素
<div id="parent">
<span id="child">我是行內(nèi)元素</span>
</div>
// 父元素是行內(nèi)元素
<span id="parent">
<span id="child">我是行內(nèi)元素</span>
</span>
CSS
// 父元素是塊級元素
.parent {
height: 300px;
width: 300px;
text-align: center;
background: skyblue;
}
// 父元素是行內(nèi)元素
.parent {
height: 300px;
width: 300px;
display: block;
text-align: center;
background: skyblue;
}
效果:
2、margin: 0 aoto
實現(xiàn)
在寬度已知的情況下可以使用margin:0 auto
,讓元素水平居中。
HTML
<div id="parent">
<div id="child">我是行內(nèi)元素</div>
</div>
CSS
.parent {
height: 300px;
width: 400px;
background: #fcc;
}
.child {
height: 100px;
width: 100px; //確保該塊級元素定寬
background: #f66;
margin: 0 auto;
}
效果:
3、table+margin實現(xiàn)
先將子元素設(shè)置為塊級表格來顯示(類似),再將其設(shè)置水平居中display:table
在表現(xiàn)上類似block
元素,但是寬度為內(nèi)容寬。
HTML
<div class="parent">
<div class="child">我是塊級元素</div>
</div>
CSS
.parent {
height: 300px;
width: 400px;
background: #fcc;
}
.child {
display: table;
background: #f66;
margin: 0 auto;
}
效果:
4、absolute+transform實現(xiàn)
首先設(shè)置父元素為相對定位,再設(shè)置子元素為絕對定位,首先設(shè)置子元素的left:50%
,然后通過向左移動子元素的一半寬度以達到水平居中。
- 定寬度,設(shè)置絕對子元素的
margin-left:-元素寬度的一半px
或者設(shè)置transform: translateX(-50%)
- 不定寬,只能使用
transform: translateX(-50%)
HTML
<div class="parent">
<div class="child">我是塊級元素</div>
</div>
CSS
.parent {
height: 300px;
width: 400px;
position: relative;
background: #fcc;
}
.child {
position: absolute;
background: #f66;
left: 50%;
transform: translateX(-50%); // 通用
/** 定寬度可使用margin-left **/
width:100px;
margin-left:-50px;
}
效果:
5、absolute+margin實現(xiàn)
通過子元素絕對定位,外加margin: 0 auto
來實現(xiàn)。
HTML
<div class="parent">
<div class="child">我是塊級元素</div>
</div>
CSS
.parent {
height: 300px;
width: 400px;
position: relative;
background: #fcc;
}
.child {
position: absolute;
background: #f66;
width: 200px;
height: 100px;
margin: 0 auto; /*水平居中*/
left: 0; /*此處不能省略,且為0*/
right: 0;/*此處不能省略,且為0*/
}
效果:
6、flexbox實現(xiàn)
使用flexbox布局,只需要給待處理的塊狀元素的父元素添加屬性 display: flex
、 justify-content: center
HTML
<div class="parent">
<div class="child">我是塊級元素</div>
</div>
CSS
.parent {
height: 300px;
width: 400px;
display: flex;
justify-content: center;
background: #fcc;
}
.child {
height: 100px;
width: 100px;
background: #f66;
}
效果:
7、flex+margin實現(xiàn)
通過flex
將父容器設(shè)置為為flex
布局,再設(shè)置子元素居中。
HTML
<div class="parent">
<div class="child">我是塊級元素</div>
</div>
CSS
.parent {
height: 300px;
width: 400px;
display: flex;
background: #fcc;
}
.child {
height: 100px;
width: 100px;
margin: 0 auto;
background: #f66;
}
效果:
最后
如果喜歡的話,歡迎收藏關(guān)注。
更多優(yōu)質(zhì)文章可以訪問GitHub博客,歡迎帥哥美女前來Star?。。?/strong>