CSS如何实现垂直居中?
通过vertical-align: middle
注意:vertical-align: middle生效的元素必须是 display: inline-block;且必须有一个兄弟元素做参照(其原理是寻找兄弟元素中最高的元素做参照让自身的中点高度和参照的中点高度对齐)

<style> .box1 { width: 600px; height: 300px; background-color: aqua; } .box2 { width: 100px; height: 100px; background-color: black; display: inline-block; vertical-align: middle; } .box3 { background-color: brown; width: 0px; height: 100%; display: inline-block; vertical-align: middle; } </style>
<body> <div class="box1"> <div class="box2"></div> <div class="box3"></div> </div> </body>
通过display: flex
注意:给父元素display: flex;给目标元素align-self: center
<style> .box1 { width: 600px; height: 300px; background-color: aqua; display: flex } .box2 { width: 100px; height: 100px; background-color: black; align-self: center; } </style>
<body> <div class="box1"> <div class="box2"></div> </div> </body>
通过line-height
注意:此方法以只父元素height,然后让目标元素的line-height等于父元素height;适用于目标元素为文本的时候
<style> .box1 { width: 600px; height: 300px; background-color: aqua; display: flex } .box2 { line-height: 300px; width: 50%; height: 50%; } </style>
<body> <div class="box1"> <p class="box2">123456</p> </div> </body>
通过transform和绝对定位
注意:此时未知父元素高度;那么就需要先将元素定位到容器的中心位置,然后使用 transform 的 translate 属性,将元素的中心和父容器的中心重合,从而实现垂直居中:
<style> .box1 { width: 600px; height: 300px; background-color: aqua; position: relative; } .box2 { width: 100px; height: 100px; background-color: beige; position: absolute; top: 50%; transform: translate(0, -50%); } </style>
<body> <div class="box1"> <div class="box2"></div> </div> </body>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用