如何解决Flex布局下div盒子换行重叠,实现每行5个自动换行
Flex布局盒子重叠问题解决:实现多行自动排列
问题描述
我尝试使用display:flex布局,但第6个盒子出现重叠问题。我希望第6-10个盒子能排列在第二行,添加第11个盒子时自动从第三行开始排列,目前布局功能可用,但样式存在重叠问题。
问题原因
当前设置了flex-direction: column(垂直方向排列)+flex-wrap: wrap+固定容器高度,这会让元素在垂直方向填满容器后向右侧换行,而非水平方向排满后换行到下一行,最终导致盒子重叠。
解决方案
调整Flex布局属性,让元素按水平方向自动换行:
- 移除
flex-direction: column(Flex默认是row水平方向) - 删除容器的固定
height,让容器高度随内容自适应 - 给每个卡片设置合适宽度,确保每行容纳指定数量的盒子(结合
gap计算宽度值)
修改后的CSS代码
.question-list-w { display: flex; gap: 10px; flex-wrap: wrap; /* 移除flex-direction: column和固定height */ } .question-list-w .horizontal-card { flex: 0 0 85px; /* 计算每行5个的宽度:(100% - 4个gap的宽度)/5 */ width: calc(20% - 8px); } .horizontal-card { display: flex; border: 1px solid #ddd; border-radius: 5px; /* 可选:优化卡片内部内容排列 */ align-items: center; padding: 0 10px; }
原HTML保持不变
<div class="question-list-w"> <div class="horizontal-card"> <div class="horizontal-card-icon"></div> <div class="horizontal-card-text">survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing traset sheets cont</div> <div class="horizontal-card-btn"> <button class="horizontal-card-btn btn-show-question" type="button" question-number="1">Show</button> <button class="horizontal-card-btn btn-start-question" question-number="1">Start</button> </div> </div> <!-- 其余卡片代码保持原结构即可 --> </div>
效果说明
修改后每行自动排列5个卡片,第6个卡片会换行到第二行,添加第11个时自动到第三行,不会出现重叠。若需调整每行卡片数量,修改width的计算值即可(比如每行4个改为calc(25% - 7.5px))。
内容的提问来源于stack exchange,提问作者user16170674
相关产品推荐
相关产品推荐

