200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > CSS 实现DIV水平垂直居中(二)

CSS 实现DIV水平垂直居中(二)

时间:2023-01-14 05:21:29

相关推荐

CSS 实现DIV水平垂直居中(二)

CSS 实现DIV垂直居中

上期介绍了CSS实现div水平居中的五种方法,下面介绍CSS实现div垂直居中的几种方法。上篇:CSS 实现DIV水平居中

首先还是和上期同样的两个div盒子,以下方法实现div垂直居中,效果如图:

1.通过padding上下留白实现视觉效果上的垂直居中。代码如下:

#d1 {width: 500px;padding: 100px 0;background-color: blanchedalmond;}#d2 {width: 200px;height: 100px;background-color: aqua;}

2.通过position定位实现div垂直居中。代码如下:

#d1 {width: 500px;height: 350px;background-color: blanchedalmond;position: relative;}#d2 {width: 200px;height: 100px;background-color: aqua;position: absolute;top: 50%;transform: translateY(-50%)}

这里的transform同样可以使用margin-top,思路和水平居中是一样的,详解可以看上一篇。

3.通过添加span标签实现div居中对齐。代码如下:

#d1 {width: 500px;height: 350px;background-color: blanchedalmond;}#d2 {width: 200px;height: 100px;background-color: aqua;display: inline-block;vertical-align: middle;}#d1 span{height: 100%;display: inline-block;vertical-align: middle;}

这里呢我们首先在d1中添加一个空的span标签,设置高度100%,再将d2和这个空的span设置为inline-block,最后利用vertical-align: middle使其垂直居中。

4.通过flex弹性布局实现div垂直居中。代码如下:

#d1 {width: 500px;height: 350px;background-color: blanchedalmond;display: flex;align-items: center;}#d2 {width: 200px;height: 100px;background-color: aqua;}

这里和上一篇的通过flex弹性布局实现div垂直居中的思路是一样的,当我们没有对主轴进行设置时,使用align-items对垂直方向进行设置。

5.通过定位实现div垂直居中。代码如下:

#d1 {width: 500px;height: 350px;background-color: blanchedalmond;position: relative;}#d2 {width: 200px;height: 100px;background-color: aqua;position: absolute;top: 0;bottom: 0;margin: auto;}

这里我们在同时设置top: 0;bottom: 0;时,利用margin: auto;自动分配d2外边距,使d2垂直居中。 0;

margin: auto;

}

这里我们在同时设置`top: 0` `bottom: 0;`时,利用`margin: auto;`自动分配d2外边距,使d2垂直居中。

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