用了一段时间的 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); }