如何将文本Zarząd对齐到卡片上方?前端布局求助
解决标题与卡片组对齐问题
问题分析
你当前的代码存在两个关键问题:
- CSS选择器
.container section无效——HTML结构中.container的子元素是h2和卡片div,没有section,导致卡片的布局样式未正确应用; - 标题
h2设置了width: 100%,但父容器.container未限制宽度,导致标题宽度撑满页面,无法和卡片组对齐。
修复代码
HTML(调整结构,新增卡片容器)
<section id="zarzad"> <div class="container"> <h2>Zarząd</h2> <div class="cards-container"> <div class="card"> <img src="https://cdn.discordapp.com/avatars/637347195623833630/71891a4d1cd9795017d08953adb04cdb.png" alt="管理团队成员"> <div class="info"> <h3>Bakłażan</h3> <p>所有者</p> </div> </div> <div class="card"> <img src="https://cdn.discordapp.com/avatars/314066973879304203/4207e8071ce2f216fac7d188e17a8502.png" alt="管理团队成员"> <div class="info"> <h3>Templariusz</h3> <p>管理团队</p> </div> </div> </div> </div> </section>
CSS(修正选择器+限制容器宽度)
#zarzad { display: flex; flex-direction: column; align-items: center; } .container { max-width: fit-content; /* 让容器宽度适配卡片组总宽度 */ } .container .cards-container { margin-top: 20px; display: flex; flex-wrap: wrap; justify-content: center; } .card { width: 200px; margin-right: 10px; margin-bottom: 20px; border: 2px solid #eee; background-color: #333; color: #eee; box-sizing: border-box; border-radius: 10px; overflow: hidden; display: flex; flex-direction: column; } #zarzad h2 { width: 100%; text-align: center; margin-bottom: 20px; } .card img { width: 100%; border-radius: 10px 10px 0 0; } .card .info { padding: 15px; } .card h3, .card p { margin: 0; color: #eee; }
效果说明
通过新增.cards-container统一包裹卡片,并给.container设置max-width: fit-content,让容器宽度自动匹配卡片组的总宽度,此时标题h2的100%宽度会和卡片组宽度完全一致,实现标题对齐在卡片上方的效果。同时修正了无效的CSS选择器,确保卡片的flex布局正常工作。
内容的提问来源于stack exchange,提问作者Maciupek
相关产品推荐
相关产品推荐

