对需要水平垂直居中的元素写css:
position : absolute;
top : 50%;
left : 50%;
transform : translate(-50%,-50%);
flex:
对父级元素写css:
单行居中:
display : flex;
justify-content : center;
align-items : center;
多行垂直居中:
display : flex;
justify-content : center;
flex-wrap : wrap/wrap-reverse;
align-items : center;
grid:
为什么不是一行代码?因为CSS设计的初衷是布局, 若你自己从系统的布局开始设计的时候, 你就会发现, 单独设计一条垂直居中的语法并不是那么优雅的, 因此, 垂直居中可以看作是业务能力拓展, 使用者可以自行封装调用.
其实现在的CSS规范中已经有了你所说的一个属性实现垂直居中的属性: https://www.w3.org/TR/css-align-3/
===========css3计算============
曾经我们还要用 “绝对定位+top:50%+margin-top:-(div height/2)px” 这样的方法
答案就是:calc() ,只要一句 “margin-top:
calc( (100vh - 360px)/2 )” 就解决了,这里的360px指代元素的高度值。
css2进化到css3的所有垂直居中方法总结:
- flex法,父元素添加 display: flex; 子元素添加 margin: auto;
- 利用calc() 数值计算
- box法,子元素添加 display: (-webkit-/-moz-/-ms-)box; box-orient: horizontal; box-pack: center; box-align: center;
- 模拟表格,父元素添加 display: table; 子元素添加 display: table-cell; vertical-align: middle
- 绝对定位,子元素添加 position: absolute; top: 50%; margin-top: -(div height/2)px;
- 利用padding或margin(边距法)
- 利用line-height(行高法),只针对文字
可以参考一下 http://blog.csdn.net/freshlover/article/details/11579669