如何让一个div里面的div垂直居中?

本文介绍了一种使用CSS实现元素垂直居中的方法。通过设置特定的display属性,可以使内部元素在其父容器内实现精确的垂直居中效果。这种方法适用于需要精细布局控制的网页设计。
.vertical-container { display : - webkit - flex ; display : flex ; - webkit - align - items : center ; align - items : center ; - webkit - justify - content : center ; justify - content : center ; }


作者:陈裕皓
链接:https://www.zhihu.com/question/24475073/answer/53921272
来源:知乎

著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

注:A套住B,在A写这个CSS则B垂直居中


在HTML中让div内多行文字垂直居中,有以下几种方法: ### 使用`display: table`和`display: table-cell` 将父元素设置为块级表格来显示(`display: table`),子元素设置为表格单元格来显示(`display: table-cell`),再设置`vertical-align: middle`。示例代码如下: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>多行文字垂直居中</title> <style> .parent { display: table; width: 400px; height: 400px; background-color: aqua; overflow: hidden; } .child { display: table-cell; vertical-align: middle; text-align: center; background-color: antiquewhite; } </style> </head> <body> <div class="parent"> <div class="child"> 你好你好你好你好你好你好你好你好你好你好你好 </div> </div> </body> </html> ``` 这种方法可以实现多行文字垂直居中,不过要注意,该方法在一些低版本浏览器中可能存在兼容性问题,比如不能兼容IE7、IE6 [^1][^4]。 ### 使用Flexbox布局 通过`display: flex`将父元素设置为弹性容器,再使用`align-items: center`实现垂直居中。示例代码如下: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>多行文字垂直居中</title> <style> .parent { display: flex; flex-direction: row; align-items: center; width: 400px; height: 400px; background-color: aqua; } </style> </head> <body> <div class="parent"> <p>你好你好你好你好你好你好你好你好你好你好你好</p> </div> </body> </html> ``` Flexbox布局是一种现代的布局方式,使用起来比较方便,但在一些旧版本浏览器中可能不被支持 [^2]。 ### 设置`line-height` 当父元素高度固定时,设置`line-height`等于父元素高度,也能实现多行文字垂直居中。示例代码如下: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>多行文字垂直居中</title> <style> .parent { height: 400px; line-height: 400px; width: 400px; background-color: aqua; } </style> </head> <body> <div class="parent"> <p>你好你好你好你好你好你好你好你好你好你好你好</p> </div> </body> </html> ``` 这种方法适用于单行或多行文字,但如果文字内容较多,可能会影响显示效果 [^3]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值