CSS实现垂直居中的7种方法
1、设定行高(line-height)2、设置伪元素::before3、absolute + transform4. 设置绝对定位5、设置display:flex6、absolute + calc7. display:table-cell实现CSS垂直居中。1、设定行高(line-height)
HTML:
<div class="parent"><span class="child">你好</span></div>
CSS:
.parent{width:200px;height:200px;border:1px solid red;}.child{width:200px;line-height: 200px; text-align: center; //水平居中display: inline-block;}
重点:父容器高度和子元素line-height
一样的数值,内容中的行内元素就会垂直居中。
2、设置伪元素::before
HTML:
<div class="parent"><div class="child"></div></div>
CSS:
.parent{width:200px;height: 200px;border:1px solid red;}.parent::before{content:'';display: inline-block;height:100%;vertical-align: middle; }.child{width:80px;height: 100px;background:red;vertical-align: middle;display: inline-block;}
重点:给父元素添加一个伪元素::before
,让这个伪元素的div
高度为100%
,这样其他div
就可垂直居中了,但div
本身就是块级元素,而vertical-align
是行内元素属性,则需要修改为inline-block
。
3、absolute + transform
HTML:
<div class="parent"><div class="child"></div></div>
CSS:
.parent{width: 200px;height: 200px;background:#ddd;position: relative;}.child{width: 100px;height: 50px;background:green;position: absolute;top: 50%;left:50%;transform: translate(-50% , -50%);}
重点:在父元素中设置相对定位position: relative
,子元素设置绝对定位position: absolute
;top和left相对父元素的50%
,与其搭配的transformse: translate(-50% , -50%)
表示X轴
和Y轴
方向水平居中。
4. 设置绝对定位
HTML:
<div class="parent"><div class="child"></div></div>
CSS:
.parent{width:200px;height: 200px;position: relative;border:1px solid red; }.child{width:50px;height: 50px;position: absolute;top:0;left:0;right:0;bottom:0;margin:auto;background:red;}
重点:子元素绝对定位position:absolute
,父元素相对定位position: relative
,将上下左右的数值都设置为0
,同时margin:auto
。绝对定位是会脱离文档流的,这点要注意一下。
5、设置display:flex
HTML:
<div class="parent"><div class="child"></div></div>
CSS:
.parent{width: 200px;height: 200px;background: grey;display: flex;justify-content: center;align-items: center;}.child{width: 100px;height: 50px;background:green;}
重点:给父元素设置display: flex
布局,水平居中justify-content: center
,垂直居中align-items: center
。
6、absolute + calc
HTML:
<div class="parent"><div class="child"></div></div>
CSS:
.parent{width: 200px;height: 200px;border:1px solid black;position: relative;}.child{width: 100px;height: 50px;position: absolute;background:red;top: calc(50% - 25px); /*垂直居中 */left:calc(50% - 50px); /*水平居中 */}
重点:父元素position
定位为relative
,子元素position
定位为absolute
。水平居中同理。calc
居中要减多少要结合到自己的宽高设置多少再进行计算。
7. display:table-cell实现CSS垂直居中。
HTML:
<div class="parent"><span class="child">你好</span></div>
CSS:
.parent{width:200px;height:200px;border:1px solid red;display: table;}.child{background:red;display: table-cell;vertical-align: middle;text-align: center;}
重点:将父元素设置display:table
,子元素table-cell
会自动撑满父元素。组合display: table-cell、vertical-align: middle、text-align: center
完成水平垂直居中。
来源