求助:如何使用Flexbox将文本定位在div.box下方?
解决方案
要实现盒子在上、文字在下的效果,核心是调整布局结构,给每个盒子和对应文字单独套一个垂直排列的容器,具体修改如下:
修改后的HTML代码
<div class="box-container"> <div class="item"> <div class="box"></div> <p>this is some subtext under an illustration or image</p> </div> <div class="item"> <div class="box"></div> <p>this is some subtext under an illustration or image</p> </div> <div class="item"> <div class="box"></div> <p>this is some subtext under an illustration or image</p> </div> <div class="item"> <div class="box"></div> <p>this is some subtext under an illustration or image</p> </div> </div>
修改后的CSS代码
.box-container { display: flex; justify-content: center; gap: 25px; } .item { /* 让每个item内部垂直排列 */ display: flex; flex-direction: column; align-items: center; width: 155px; /* 和盒子宽度保持一致,确保文本换行对齐 */ } .box { height: 160px; width: 155px; border: 3px solid #3882f6; border-radius: 10px; margin-bottom: 8px; /* 给盒子和文字之间加一点间距 */ } .item p { text-align: center; margin: 0; }
关键调整点
- 新增
.item容器,通过flex-direction: column实现盒子与文字的纵向堆叠,align-items: center保证内容居中对齐 - 给
.item设置固定宽度,避免文本换行后超出盒子范围 - 将p标签从.box中移出,让文字独立显示在盒子下方
内容的提问来源于stack exchange,提问作者Hilow
相关产品推荐
相关产品推荐

