如何解决flex容器内header无法置于flex项目上方并居中的问题
问题原因
你当前的问题根源是flex容器.big-location-container默认沿水平主轴排列所有子元素,所以<h2>标题和三个.location-container卡片会被当成同级flex项排在同一行。
解决方案
按照以下步骤修改即可实现需求:
- 调整外层容器的flex排列方向为垂直方向,新增
flex-direction: column属性,让子元素从上到下排布 - 把三个卡片元素单独包裹在一个新的容器节点内,给这个新容器设置
display: flex,实现三个卡片的横向排列 - 按需调整标题与卡片容器的间距、对齐属性即可
修改后的完整CSS代码
.big-location-container { height: 500px; width: 1200px; margin: 0 auto; display: flex; justify-content: center; align-items: center; flex-direction: column; /* 新增:子元素垂直排列 */ background-color: white; } /* 新增:包裹三个卡片的容器样式 */ .locations-wrapper { display: flex; } .location-container { width: 300px; height: 50%; margin: 15px 40px; background-color: black; opacity: 1; color: white; /* 补充:黑背景配白字才能看清内容 */ } /* 可选:调整标题的下边距 */ .big-location-container h2 { margin-bottom: 20px; }
修改后的完整HTML代码
<div class="big-location-container"> <h2>Locations</h2> <!-- 新增卡片包裹层 --> <div class="locations-wrapper"> <div class="location-container"> <h3>Downtown</h3> <p>384 West 4th St</p> <p>Suite 108</p> <p>Portland, Maine</p> </div> <div class="location-container"> <h3>East Bayside</h3> <p>3433 Phisherman's Avenue</p> <p>(Northwest Corner)</p> <p>Portland, Maine</p> </div> <div class="location-container"> <h3>Oakdale</h3> <p>515 Crescent Avenue</p> <p>Second Floor</p> <p>Portland, Maine</p> </div> </div> </div>
内容的提问来源于stack exchange,提问作者Lena.S98
相关产品推荐
相关产品推荐

