如何将背景图设为Flex容器并实现三个黑色文本框横向排列
Flex布局实现背景图上横向文本框的解决方案
问题
需要在背景图上方叠加三个黑底白字的文本框,通过Flex实现横向排列,但当前代码中文本框呈现纵向堆叠状态。
问题分析
- Flex布局属性错误应用在了
<img>元素上,而非文本框的父容器 - 背景图的定位方式占据布局流,挤压文本框的排列空间
- 文本框自身设置
display:flex但未配置布局方向,且父容器无横向排列规则
修改后的代码
HTML
<!--locations--> <section> <div class="locations"> <img class="img-locations-background" src="C:\Users\vkuzma\OneDrive - Compass Energy Systems Ltd\Desktop\VS Sheet\Tea Cozy\Photos\img-locations-background.jpg"> <h1 class="loca">Locations</h1> <div class="location-boxes"> <div id="box-1"> <h3>Downtown</h3> <p>384 West 4th St</p> <p>Suite 108</p> <p>Portland, Maine</p> </div> <div id="box-2"> <h3>East Bayside</h3> <p>3433 Phisherman's Avenue</p> <p>(Northwest Corner)</p> <p>Portland, Maine</p> </div> <div id="box-3"> <h3>Oakdale</h3> <p>3433 Phisherman's Avenue</p> <p>Second Floor</p> <p>Portland, Maine</p> </div> </div> </div> </section> </body>
CSS
/* locations */ .locations { position: relative; height: 500px; display: flex; flex-direction: column; align-items: center; justify-content: center; } .img-locations-background { position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; opacity: 0.9; z-index: -1; /* 将背景图置于底层 */ } .loca { font-family: Helvetica; color: seashell; margin-bottom: 15px; text-align: center; } .location-boxes { display: flex; gap: 20px; /* 控制文本框之间的间距 */ width: 90%; justify-content: center; } #box-1, #box-2, #box-3 { color: seashell; font-family: Helvetica; background-color: black; width: 300px; height: 200px; display: flex; flex-direction: column; justify-content: space-around; align-items: center; padding: 10px; box-sizing: border-box; }
修改说明
- 将背景图设置为绝对定位并置于底层(
z-index: -1),不占用布局流空间 - 给文本框添加统一父容器
.location-boxes,设置display:flex实现横向排列,用gap控制间距 - 文本框内部设置
flex-direction: column,让内容垂直居中排列 - 父容器
.locations设置Flex布局,确保标题和文本框容器整体垂直居中
内容的提问来源于stack exchange,提问作者Tsumind
相关产品推荐
相关产品推荐

