用了一段時間的 material-ui,都不多本身動手寫原生的樣式了。但 html, css, js 始終是前端的三大基礎,這周忽然想到 CSS 水平居中方案,由於用多了 flex
和 margin: auto
等這類方案解決,在回顧還有還有幾種方案能夠解決,因而打算溫故知新,從新打下代碼,寫下該文做爲筆記。css
html 代碼html
<div class="parent"> <div class="child"></div> </div>
css 代碼前端
.parent { width: 300px; height: 300px; background-color: blue; } .child { width: 100px; height: 100px; background-color: red; }
下面代碼基於上述代碼增長,不會再重複寫。要實現的效果是讓子元素在父元素中水平垂直居中
git
.parent { display: flex; justify-content: center; align-items: center; }
這是最經典的用法了,不過,也能夠有另外一種寫法實現:github
.parent { display: flex; } .child { align-self: center; margin: auto; }
該方法適用於知道固定寬高的狀況。佈局
.parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; margin-top: -50px; margin-left: -50px; }
.parent { position: relative; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
.parent { position: relative; } .child { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; }
該方法適用於知道固定寬高的狀況。flex
.parent { position: relative; } .child { position: absolute; top: calc(50% - 50px); left: calc(50% - 50px); }
.parent { text-align: center; line-height: 300px; /* 等於 parent 的 height */ } .child { display: inline-block; vertical-align: middle; line-height: initial; /* 這樣 child 內的文字就不會超出跑到下面 */ }
.parent { display: table-cell; text-align: center; vertical-align: middle; } .child { display: inline-block; }
.parent { display: grid; } .child { align-self: center; justify-self: center; }
.parent { writing-mode: vertical-lr; text-align: center; } .child { writing-mode: horizontal-tb; display: inline-block; margin: 0 calc(50% - 50px); }