如何实现蓝色盒子并排且位于指定文本下方的布局?
实现蓝色盒子并排且位于文本下方的方案
要达成需求,你可以通过调整HTML结构并修改CSS布局设置来实现,具体如下:
修改后的代码
CSS 代码
.container2 { height: 45vh; background-color: white; position: relative; padding-top: 30px; display: flex; justify-content: center; flex-direction: column; /* 改为垂直排列子元素 */ align-items: center; /* 子元素水平居中 */ } .text5 { font-size: 36px; font-weight: 800; margin-bottom: 20px; /* 文本和盒子之间留间距 */ } .box-container { display: flex; gap: 15px; /* 控制盒子之间的间距 */ } #box1, #box2, #box3, #box4 { border: 2px solid #3882F6; height: 50px; width: 50px; }
HTML 代码
<div class="container2"> <div class="text5">Some random information.</div> <!-- 用容器包裹盒子,方便统一控制布局 --> <div class="box-container"> <div class="box1" id="box1"></div> <div class="box2" id="box2"></div> <div class="box3" id="box3"></div> <div class="box4" id="box4"></div> </div> </div>
关键修改说明
- 调整HTML结构:将文本和盒子分开放置,用
box-container统一包裹所有盒子,明确上下层级关系 - 修改
container2的flex-direction为column,让文本和盒子容器垂直排列,实现文本在上、盒子在下的效果 - 给
box-container设置display: flex,让内部盒子自动横向并排,同时用gap属性控制盒子间的间距,优化视觉体验 - 给
text5添加margin-bottom,让文本和盒子之间保持合适的距离
内容的提问来源于stack exchange,提问作者Tuan Nguyen
相关产品推荐
相关产品推荐

