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垂直居中。