.parent {
text-align: center;
}
複製代碼
.son {
margin: 0 auto;
}
複製代碼
.parent{
width:fit-content;
margin:0 auto;
}
.son {
float: left;
}
複製代碼
1) flex 2012版css
.parent {
display: flex;
justify-content: center;
}
複製代碼
2)flex 2009版segmentfault
.parent {
display: box;
box-orient: horizontal;
box-pack: center;
}
複製代碼
1)transform瀏覽器
.son {
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
複製代碼
2)left: 50%bash
.son {
position: absolute;
width: 寬度;
left: 50%;
margin-left: -0.5*寬度
}
複製代碼
3)left/right: 0佈局
.son {
position: absolute;
width: 寬度;
left: 0;
right: 0;
margin: 0 auto;
}
複製代碼
以上是 CSS 水平居中的 8 種方法。post
.parent {
height: 高度;
}
.son {
line-height: 高度;
}
複製代碼
注:① 子元素 line-height 值爲父元素 height 值。② 單行文本。flex
.parent::after, .son{
display:inline-block;
vertical-align:middle;
}
.parent::after{
content:'';
height:100%;
}
複製代碼
適應 IE7。ui
.parent {
display: table;
}
.son {
display: table-cell;
vertical-align: middle;
}
複製代碼
優勢spa
缺點3d
1)flex 2012版
.parent {
display: flex;
align-items: center;
}
複製代碼
優勢
缺點
2)flex 2009版
.parent {
display: box;
box-orien: vertical;
box-pack: center;
}
複製代碼
優勢
缺點
1)transform
.son {
position: absolute;
top: 50%;
transform: translate( 0, -50%);
}
複製代碼
優勢
缺點
2)top: 50%
.son {
position: absolute;
top: 50%;
height: 高度;
margin-top: -0.5高度;
}
複製代碼
優勢
缺點
3)top/bottom: 0;
.son {
position: absolute;
top: 0;
bottom: 0;
margin: auto 0;
}
複製代碼
優勢
缺點
以上是 CSS 垂直居中的 8 種方法及其優缺點。
其中,
同時適用於水平居中和垂直居中。
但願幫助到了你。
歡迎討論。
٩(๑❛ᴗ❛๑)۶
感謝@ape-casear,@鬥鷹 的指正!
也歡迎你們一塊兒將 CSS 的居中總結得更好!
參考文獻
[1] louis. 16種方法實現水平居中垂直居中[OL],2017-04-20.
[2] 慢思考快行動. css設置垂直居中[OL], 2017-09-03.