如何实现div元素垂直对齐?附现有CSS与HTML代码示例
div垂直居中效果实现方案
你当前代码的核心问题是父容器#mission-picture没有配置flex布局,无法控制子元素#image-text的垂直对齐逻辑,按如下修改即可达成目标效果:
调整后的CSS代码
1. 父容器#mission-picture新增flex布局属性
#mission-picture{ background-image: url("https://content.codecademy.com/courses/freelance-1/unit-4/img-mission-background.jpg"); background-repeat: no-repeat; background-size: cover; width: 1200px; height: 700px; margin: 0 auto; /* 新增以下3行属性 */ display: flex; justify-content: center; align-items: center; }
2. 子容器#image-text调整flex属性(可选优化)
你原有代码里的align-content不适用于当前单列flex布局的对齐需求,调整为以下配置即可让内部的h2、h4文本也完全居中:
#image-text { background-color: black; color: white; width: 100%; text-align: center; display: flex; flex-direction: column; justify-content: center; align-items: center; }
原理说明
flex容器默认主轴为水平方向,justify-content: center实现子元素水平居中,align-items: center实现子元素垂直居中,最终#image-text会固定在背景图的垂直水平居中位置,和示例效果一致。
内容的提问来源于stack exchange,提问作者Grafcar
相关产品推荐
相关产品推荐

