水平垂直居中有好多種實現方式,主要就分爲兩類:不定寬高
和定寬高
,以在body下插入一個div爲例:
- 定寬高
- 使用定位+margin
element.style { position: absolute; left: 50%; top: 50%; margin-left: -250px; margin-top: -250px; width: 500px; height: 500px; background: yellow; z-index: 1; }
- 使用定位+transfrom
element.style { position: absolute; left: 50%; top: 50%; width: 500px; height: 500px; background: yellow; z-index: 1; transform: translate3d(-50%,-50%,0); }
- table-cell 方式
div.parent-box { display: table; width: 100%; } div.parent { display: table-cell; height: 200px; width: 200px; background-color: orange; text-align: center; vertical-align: middle; } div.child { display: inline-block; width: 100px; height: 100px; background-color: blue; }
table-cell 是不支持設置 width: 100%; 想讓 .parent 和 其容器寬度一致最好設置一個 dispaly: table; 父容器。<div class="parent-fix"> <div class="parent"> <div class="child">DEMO</div> </div> </div>
- calc方式
.parent { border: 1px solid; width: 1000px; height: 1000px; } .child { position: relative; border: 1px solid; width: 100px; height: 100px; top: calc(50% - 50px); left: calc(50% - 50px); }
-
不定寬高:不定寬高的方法基本都適用於定寬高的情況,這裏把div的寬高按照內容展開,使用定位+transform同樣是適用的
div.parent { position: reletive; } element.style { position: absolute; left: 50%; top: 50%; background: yellow; z-index: 1; transform: translate3d(-50%,-50%,0); }
-
flex、grid方法:
div.parent{ display:flex; } div.child{ margin:auto; }
// 子元素自動垂直水平居中 div.parent { display: flex; justify-content: center; align-items: center; }
或者
div.parent{ display:flex; } div.child{ margin:auto; }
-
static 方法
div.parent { font-size: 0; text-align: center; &::before { content: ""; display: inline-block; width: 0; height: 100%; vertical-align: middle; } } div.child{ display: inline-block; vertical-align: middle; }
此法來自張鑫旭的《CSS世界》,原理就是:設置
inline-block
和vertical-align:middle
後,裏面的元素會基於中間的文字準線居中對齊(學生時代的英語本子裏面寫字母,都是4條線形成三個空白區域,文字的對齊就是根據這幾條線的)vertical-align
更多信息可以看看張鑫旭博文; 然後,由於僞類是position:static(默認)
的,那麼僞類撐開了父元素的基準線(高度是100%),使得此時文字的基準線就是整個div.parent的中心了,另外vertical-align
隻影響inline
或者inline-block
的,所以div.child設置vertical-align
就能居中了。