8 ways vertically centered CSS
8 ways vertically centered CSS
1, by verticle-align: middle achieve CSS vertically.
by vertical-align: middle method is most commonly used to achieve CSS vertically centered, but there is little need extra attention, the premise is to take effect vertical display elements: inline-block.
2, through the display: flex achieve CSS vertically.
More and more popular programs: "flex display" to achieve the level of CSS centered as more and more browser compatible flexbox properties in CSS, so by now.
By display: CSS method implemented flex vertically centered parent element is to display: flex; and the child elements align-self: center;
The CSS is centered horizontally with the principle is the same, but some differences in the flex-direction, one row (default value), the other is a column.
3, pseudo elements: before achieved CSS vertically.
DETAILED DESCRIPTION pseudo-element is the parent element is added: before, so that the sub-elements to achieve vertical centering.
4, through the display: table-cell CSS implemented vertically.
Parent elements to display: table, sub-element display: table-cell CSS way to achieve vertical center.
5, realized by hidden nodes CSS vertical centering.
Creating a hidden node #hide, so that the height of the hidden node value of the remaining half of the height of the can.
This approach also applies to CSS centered horizontally, the same principle.
CSS垂直居中的8种方法
1、通过verticle-align:middle实现CSS垂直居中。
通过vertical-align:middle实现CSS垂直居中是最常使用的方法,但是有一点需要格外注意,vertical生效的前提是元素的display:inline-block。
2、通过display:flex实现CSS垂直居中。
随着越来越多浏览器兼容CSS中的flexbox特性,所以现在通过“display:flex”实现CSS水平居中的方案也越来越受青睐。
通过display:flex实现CSS垂直居中的方法是给父元素display:flex;而子元素align-self:center;
这个跟CSS水平居中的原理是一样的,只是在flex-direction上有所差别,一个是row(默认值),另外一个是column。
3、通过伪元素:before实现CSS垂直居中。
具体方式是为父元素添加伪元素:before,使得子元素实现垂直居中。
4、通过display:table-cell实现CSS垂直居中。
给父元素display:table,子元素display:table-cell的方式实现CSS垂直居中。
5、通过隐藏节点实现CSS垂直居中。
创建一个隐藏节点#hide,使得隐藏节点的height值为剩余高度的一半即可。
这种方法也适用于CSS水平居中,原理一样。