分成 塊級元素 和 行內(nèi)元素 進(jìn)行總結(jié)
塊級元素
flex布局:
????具體的做法就是把父元素的屬性: jusity-content(主軸對齊方式) 和 align-items(交叉軸單行對齊)? 的值設(shè)置為 center
效果圖:
Css代碼:
#warp{
????width:100%;
????height:400px;
????background-color:antiquewhite;
????display:flex;
????/* 主軸的對齊方式 */
????justify-content:center;
????/* 交叉軸上的單行對齊 */
????align-items:center;
}
.center{
????width:160px;
????height:220px;
????background-color:azure;
????text-align:center;
?}
.centerspan{
????line-height:220px;
}
Html代碼:
<divid="warp">
????<divclass="center">
????????<span>實現(xiàn)水平垂直居中</span>
????</div>
</div>
絕對定位(position: absolute)+ 負(fù)margin(這種方式需要知道元素的寬高):
效果圖:
Css代碼:
.center{
????width:400px;
????height:200px;
????background-color:beige;
????position:absolute;
????top:50%;
????left:50%;
????margin-top:-100px;
????margin-left:-200px;
????text-align:center;
?}
.centerspan{
????line-height:200px;
?}
Html代碼:
<divclass="center">
????<span>水平垂直居中</span>
</div>
絕對定位(position: absolute)+ transform: translate()屬性:
效果圖:
代碼:
.center{
????width:380px;
????height:400px;
????background-color:#ccc;
????position:absolute;
????top:50%;
????left:50%;
????transform:translate(-50%,-50%);
????text-align:center;
?}
總結(jié):?
????其實后面兩種原理是相同的,通過絕對定位設(shè)置top和left為50%之后,再考慮處理元素自身的寬高;區(qū)別是負(fù)margin的方式需要知道具體的值才能設(shè)置八毯,而transform: translate()設(shè)置百分比就可以皮获,不需要知道具體的值
其他:
如果只需要水平居中:給對應(yīng)的塊級元素設(shè)置 margin: 0 auto;? 即可
行內(nèi)元素
? ? 1焙蚓、在父元素上設(shè)置:text-align: center;? 實現(xiàn)水平居中;設(shè)置元素的 line-height 的值等于父元素的 height 的值實現(xiàn)垂直居中洒宝,這應(yīng)該是我們平時用的比較多的一種
? ? 2购公、在父元素上設(shè)置:text-align: center;? 實現(xiàn)水平居中;再給父元素設(shè)置 display: table;? 行內(nèi)元素設(shè)置 display: table-cell;? vertical-align: middle; 實現(xiàn)垂直居中
效果圖:
Css代碼:
.warp{
????display:table;
????width:200px;
????height:300px;
????background-color:blanchedalmond;
????text-align:center;
?}
.warpspan{
????display:table-cell;
????vertical-align:middle;
?}
Html代碼:
<divclass="warp">
????<span>設(shè)置元素水平垂直居中</span>
</div>
3雁歌、給行內(nèi)元素一個沒有寬高的父元素宏浩,利用 flex 布局使其父元素水平垂直居中即可
效果圖:
Css代碼:
*{margin:0;padding:0;list-style:none;}
.container{
????margin:100px00100px;
????width:400px;
????height:400px;
????background-color:blanchedalmond;
????display:flex;
????justify-content:center;
????align-items:center;
?}
.center{
????/* padding: 10px; */
????background-color:#ccc;
?}
Html代碼:
<divclass="container">
????<divclass="center">
????????<span>元素水平垂直居中</span>
????</div>
</div>