如何让中心Div在周围Div增删时保持居中不偏移?
实现永久居中的加号卡片,笔记围绕其排列
问题解决思路
之前的Grid布局写法存在语法错误(grid-template-areas的逗号、单引号使用不当),且固定行列模板无法适配动态增删的笔记卡片;使用position: absolute会让加号卡片脱离文档流,导致被其他卡片覆盖。
正确的做法是利用Grid布局的单元格定位能力,将加号卡片固定在网格中心位置,其他笔记卡片自动填充剩余网格空间,全程保持文档流布局,避免覆盖问题。
修改后的完整代码
CSS 部分
* { margin: 0; padding: 0; box-sizing: border-box; font-family: Arial, Helvetica, sans-serif; } body { background-color: #ffffff; color: black; min-height: 100vh; border: #008f4b solid 6px; padding: 20px; } .nav_container { display: flex; justify-content: center; margin-bottom: 20px; } .nav { width: 300px; } ul { list-style-type: none; background-color: #008f4b; border-radius: 20px; display: flex; border: #024731 solid 3px; } li { color: white; text-align: center; padding: 10px 16px; cursor: pointer; flex: 1; display: flex; align-items: center; justify-content: center; } li:hover { background-color: #00b85f; } .notes_container { display: flex; justify-content: center; width: 100%; } .notes_wrapper { display: grid; grid-template-columns: repeat(5, 200px); /* 5列,每列宽度匹配卡片 */ grid-gap: 20px; /* 统一控制卡片间距 */ justify-content: center; } .note_card { padding: 6px; height: 40px; background-color: #ebebeb; font-size: 24px; width: 100%; /* 填充网格单元格 */ } .add_card { grid-column: 3 / 4; /* 定位到第3列 */ grid-row: 1 / 2; /* 定位到第1行 */ padding: 40px 20px; font-size: 100px; text-align: center; background-color: #ebebeb; cursor: pointer; z-index: 1; /* 确保优先级,避免被覆盖 */ }
HTML 部分
<div class="nav_container"> <div class="nav"> <ul> <li>All</li> <li>Recent</li> <li>Pinned</li> <li>Search</li> </ul> </div> </div> <div class="notes_container"> <div class="notes_wrapper"> <div class="note_card"> <h3>Notes</h3> </div> <div class="note_card"> <h3>Notes</h3> </div> <div class="add_card">+</div> <div class="note_card"> <h3>Notes</h3> </div> <div class="note_card"> <h3>Notes</h3> </div> <div class="note_card"> <h3>Notes</h3> </div> <div class="note_card"> <h3>Notes</h3> </div> <!-- 新增的note_card会自动填充网格剩余位置 --> <div class="note_card"> <h3>New Note</h3> </div> </div> </div>
关键修改说明
- 网格定位:通过
grid-column: 3 / 4和grid-row: 1 / 2将加号卡片固定在5列网格的中心单元格,无论增删多少笔记卡片,这个位置始终保留给加号。 - 间距控制:移除卡片的
margin,改用grid-gap统一管理网格间距,避免布局偏移。 - 自适应填充:笔记卡片设置
width: 100%填充网格单元格,新增的卡片会自动按网格顺序填充剩余空间,不会覆盖加号卡片。
内容的提问来源于stack exchange,提问作者Thomas Silver
相关产品推荐
相关产品推荐

