一.水平居中
(1)文本圖片行內(nèi)元素水平居中
.inlineCenter{
text-align:center;
background:#eeeb38;
}
<div class = "inlineCenter">
行內(nèi)元素居中
</div>

行內(nèi)元素居中.png
2.確定寬度的塊級(jí)元素水平居中
設(shè)置左右邊距auto和寬度
.blockCenter{
margin-left: auto;
margin-right: auto;
width: 20%;
text-align: center;
background: #eee;
}
<div class="blockCenter">
確定寬度的塊級(jí)元素居中
</div>

確定寬度塊級(jí)元素.png
(3)寬度不定的塊級(jí)元素水平居中
a.設(shè)置元素display:inline-block,text-align:center
缺點(diǎn):失去塊級(jí)元素特性
b.使用相對(duì)定位居中:
父元素:{float:left,position:relative,left:50%}
子元素:{position:relative,left:-50%}
缺點(diǎn):文本脫離文檔流,對(duì)后面布局會(huì)有影響
.blockCenter{
float: left;
position: relative;
left:50%
}
.block{
position: relative;
left:-50%;
background: #59aecc;
}
<div class="blockCenter1">
<div class="block">
塊居中,父元素設(shè)置左浮動(dòng),相對(duì)定位,左邊50%,子元素相對(duì)定位,左邊-50%
</div>
</div>

相對(duì)定位塊居中.png
(4) 使用flex實(shí)現(xiàn)水平居中
彈性盒模型可以方便地實(shí)現(xiàn)水平和垂直居中,
效果可作用于多個(gè)元素,推薦使用flex進(jìn)行水平和垂直居中
.flexCenter{
display: flex;
justify-content: center; /*設(shè)置主軸對(duì)齊方式*/
background: #cc996a;
}
<div class="flexCenter">
<div style="background: #46ee24">
使用flex實(shí)現(xiàn)居中
</div>
<div style="background: #cc4f28">
使用flex實(shí)現(xiàn)居中
</div>
</div>

使用flex實(shí)現(xiàn)居中.png
二.垂直居中
(1) 父元素高度不確定的文本、圖片、塊級(jí)元素的垂直居中
此時(shí)需要文本,圖片,塊級(jí)元素將父元素“撐開”
設(shè)置父元素上下padding相同即可
.verticalCenter{
padding: 20px 0;
background: #59aecc;
}
<div class="verticalCenter">
<div style="background: #eee;width: 10%;height:50px">
垂直居中
</div>
</div>

父元素高度不定的垂直居中.png
(2)父元素高度確定的單行文本的垂直居中
通過給父元素設(shè)置line-height來實(shí)現(xiàn)
line-height值和父元素高度值相同
.verticalCenter{
padding: 20px 0;
background: #59aecc;
}
.textVerticalCenter{
background: #e0ee0d;
width: 10%;
height:50px;
line-height: 50px;
}
<div class="verticalCenter">
<div class = "textVerticalCenter">
垂直居中
</div>
</div>

文字居中.png
(3)使用flex實(shí)現(xiàn)垂直居中
設(shè)置主軸為垂直方向,設(shè)置主軸的對(duì)齊方式為居中
下面用flex實(shí)現(xiàn)了水平和垂直方向都居中
.flexVerticalCenter{
height: 100px;
display: flex;
flex-direction: column; /*設(shè)置主軸為垂直方向*/
justify-content: center;/*設(shè)置主軸對(duì)齊方式*/
align-items: center; /*設(shè)置交叉軸對(duì)齊方式*/
background: #cc996a;
}
<div class="flexVerticalCenter">
<div style="background: #46ee24">
使用flex實(shí)現(xiàn)居中
</div>
<div style="background: #cc4f28">
使用flex實(shí)現(xiàn)居中
</div>
</div>

flex實(shí)現(xiàn)垂直居中.png