1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > CSS实现垂直居中的7种方法

CSS实现垂直居中的7种方法

时间:2024-06-06 01:28:11

相关推荐

CSS实现垂直居中的7种方法

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完成水平垂直居中。

来源

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。