1.背景介紹
居中是前端排版的一個重要話題,今天我們就來梳理一下垂直居中的方法。
2.知識剖析
布局的解決方案,基于盒狀模型,依賴 display 屬性 + position屬性 + float屬性+flexbox,咱們就從這幾點入手。
3.常見問題
垂直居中的方式?
4.解決方案
HTML如下:
<div class="out">
<div class="in">nihaoa</div>
</div>
默認的CSS如下:
.out {
width: 300px;
height: 300px;
background-color: red;
}
.in {
background-color: yellow;
}
①子元素 line-height: 100%,代碼少,兼容性好,但子元素背景色覆蓋了父元素:
.in {
line-height: 100%;
}
②子元素absolute+auto,兼容性好,但需要設置子元素的高度:
.out {
position: relative;
}
.in {
position: absolute;
top: 0;
bottom: 0;
margin: auto;
height: 20px;
}
③ 子元素 top+margin-top,兼容性好,但需要設置子元素的高度 :
.out {
position: relative;
}
.in {
position: absolute;
top: 50%;
height: 20px;
margin-top: -10px;
}
④ 子元素absolute+ translateY,無需設置子元素的高度,但兼容性不好:
.out {
position: relative;
}
.in {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
⑤ 子元素top: calc(),只需設置子元素,但需要知道子元素的高度,且兼容性不好:
.in {
position: relative;
height: 20px;
top: calc(50% - 10px);
}
⑥ 父元素 display: flex;設置很簡單,但兼容性不好
.out {
display: flex;
align-items: center;
}
⑦ 父元素 display: flex;+子元素margin:auto;設置簡單,比6稍微復雜,但同樣兼容性不好:
.out {
display: flex;
}
.in {
margin: auto 0;
}
⑧ table布局,兼容性好,但子元素背景色會覆蓋父元素,且性能不好:
.out {
display: table;
}
.in {
display: table-cell;
vertical-align: middle;
}
⑨ 兼容性好,但需要知道父元素高度,且比較復雜:
.out:after {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.in {
display: inline;
vertical-align: middle;
}
5.編碼實戰(zhàn)
如上
6.擴展思考
如何水平居中?
方法如下:
①子元素margin: auto;
.in {
margin: auto;
width: 4em;
}
②對于行內(nèi)元素 text-align: center;
.in {
text-align: center;
}
③和②相似
.out {
text-align: center;
}
.in {
display: inline-block;
}
④絕對定位+left+ margin-left
.out {
position: relative;
}
.in {
position: absolute;
left: 50%;
width: 5em;
margin-left: -2.5em;
}
⑤絕對定位+left+ translatex
.out {
position: relative;
}
.in {
position: absolute;
left: 50%;
transform: translatex(-50%);
}
⑥子元素display: table;
.in {
display: table;
margin: auto;
}
⑦父元素 display: flex;+子元素margin:auto;
.out {
display: flex;
}
.in {
margin: 0 auto;
height: 20px;
}
⑧父元素display: flex;
.out {
display: flex;
justify-content: center;
}
.in {
height: 20px;
}
7.參考文獻
HTML與CSS布局技巧——垂直居中
http://lotabout.me/2016/CSS-vertical-center/
http://y.dobit.top/Detail/162.html