如何将h2标题放置在已居中的div元素组上方
问题描述
我开发了一个小型网站,其中有一个区域包含三个居中排列的div,我正尝试将<h2>放置在这组div的上方,预期效果如下:
目前我能实现的最优效果是在#locationsbg上使用display: flex;和flex-direction: column;,让Locations对应的<h2>和下方div一同居中,暂时未达到预期,所以我先注释掉了该h2元素。
现有代码
CSS代码
* { background-color: black; font-family: Helvetica; color: seashell; opacity: 0.9; font-size: 22px; text-align: center; } #locations { display: inline-flex; background-color: transparent; } #locationsbg { margin: 0 auto; height: 500px; width: 1200px; background-image: url(https://content.codecademy.com/courses/freelance-1/unit-4/img-locations-background.jpg); background-repeat: no-repeat; background-position: center; background-size: cover; display: flex; align-items: center; justify-content: center; } #locationsbg h2 { background-color: transparent; position: relative; top: 40px; } #locations div { max-height: 300px; width: 300px; display: flex; flex-direction: column; margin-left: 40px; opacity: 1; }
HTML代码
<section id="locationsbg"> <!--<h2>Locations</h2> 该元素需要放在居中div组的上方,而非整体居中--> <div id="locations"> <div> <h3>Downtown</h3> <p>384 West 4th St</p> <p>Suite 108</p> <p>Portland, Maine</p> </div> <div> <h3>East Bayside</h3> <p>3433 Phisherman's Avenue</p> <p>(Northwest Corner)</p> <p>Portland, Maine</p> </div> <div> <h3>Oakdale</h3> <p>515 Crescent Avenue</p> <p>Second Floor</p> <p>Portland, Maine</p> </div> </div> </section>
解决方案
调整思路
只需要微调flex布局的属性,修正h2的定位方式,再补全一个小的边距优化即可实现效果:
- 给
#locationsbg加上flex-direction: column属性,让内部的h2和div组沿纵向排列,原本的align-items: center会自动让两个元素都水平居中 - 删掉
#locationsbg h2的相对定位偏移,改用margin-bottom控制和下方卡片组的间距,避免定位偏移导致的布局错位 - 新增规则去掉第一个卡片的左外边距,避免三个卡片整体向右偏移
调整后的CSS代码(仅修改部分)
#locationsbg { margin: 0 auto; height: 500px; width: 1200px; background-image: url(https://content.codecademy.com/courses/freelance-1/unit-4/img-locations-background.jpg); background-repeat: no-repeat; background-position: center; background-size: cover; display: flex; align-items: center; justify-content: center; flex-direction: column; /* 新增属性 */ } #locationsbg h2 { background-color: transparent; margin-bottom: 15px; /* 替换原来的top: 40px */ font-size: 32px; /* 可选,调整字号区分标题层级 */ } /* 新增规则修正卡片组偏移问题 */ #locations div:first-child { margin-left: 0; }
HTML修改
直接取消<h2>Locations</h2>的注释即可,不需要改动其他结构。
内容的提问来源于stack exchange,提问作者Tknoobs
相关产品推荐
相关产品推荐

