📖 核心概念
- Flexbox:一维布局利器
- Grid:二维布局王者
- Flex vs Grid:何时用哪个?
- 常见布局模式实现
- 对齐、间距与分布
- 响应式布局技巧
💻 代码实现
Flexbox常用布局
✅ css
/* 导航栏布局 */
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 2rem;
background: #1e293b;
}
.navbar-logo { flex-shrink: 0; }
.navbar-links {
display: flex;
gap: 1.5rem;
list-style: none;
}
/* 卡片列表 */
.card-list {
display: flex;
flex-wrap: wrap;
gap: 1.5rem;
}
.card {
flex: 1 1 300px; /* 弹性增长,最小300px */
max-width: 400px;
background: #1e293b;
border-radius: 12px;
padding: 1.5rem;
}
/* 圣杯布局 */
.holy-grail {
display: flex;
min-height: 100vh;
flex-direction: column;
}
.holy-grail main {
display: flex;
flex: 1;
}
.holy-grail .sidebar-left { width: 200px; order: -1; }
.holy-grail .content { flex: 1; }
.holy-grail .sidebar-right { width: 200px; }
/* 居中神器 */
.center-me {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
Grid高级布局
✅ css
/* 12列网格系统 */
.grid-system {
display: grid;
grid-template-columns: repeat(12, 1fr);
gap: 1rem;
}
.col-6 { grid-column: span 6; }
.col-4 { grid-column: span 4; }
.col-8 { grid-column: span 8; }
/* 仪表盘布局 */
.dashboard {
display: grid;
grid-template-columns: 250px 1fr 300px;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header header"
"sidebar content aside"
"footer footer footer";
min-height: 100vh;
gap: 0;
}
.dashboard-header { grid-area: header; }
.dashboard-sidebar { grid-area: sidebar; }
.dashboard-content { grid-area: content; }
.dashboard-aside { grid-area: aside; }
.dashboard-footer { grid-area: footer; }
/* 杂志排版 */
.magazine {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: 200px;
gap: 1rem;
}
.magazine .featured {
grid-column: span 2;
grid-row: span 2;
}
/* 响应式Grid */
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 1.5rem;
}
🔍 Flex与Grid实战进阶
Flexbox常见问题与解决方案
在实际开发中,Flexbox经常会遇到一些让人困惑的问题。以下是最常见的几个场景及其解决方案:
- flex: 1 vs flex-grow: 1 — flex: 1 等同于 flex: 1 1 0%(可以收缩,初始尺寸为0),而 flex-grow: 1 只是 flex: 1 0 0(不能收缩)。当内容超出容器时,flex: 1 会自动缩小,flex-grow: 1 则不会。
- min-width: 0 的魔法 — Flex子项默认min-width为auto,当内容过长时不会缩小。添加 min-width: 0 可以让子项正确缩小。
- 安全使用flex-basis — 始终使用flex简写属性(flex: 1 1 200px)而不是单独设置flex-basis,避免与flex-grow/shrink冲突。
Grid子网格(Subgrid)
CSS Grid Level 2引入了subgrid,允许子网格继承父网格的轨道定义。这对于需要内部对齐的卡片布局非常有用:
Subgrid对齐
✅ css
.card-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 1rem;
}
.card {
display: grid;
grid-row: span 3; /* 标题/内容/操作 三行 */
grid-template-rows: subgrid; /* 继承父网格行 */
gap: 0;
}
/* 所有卡片的标题、内容、操作行自动对齐 */
布局调试技巧
当布局不符合预期时,可以使用以下方法快速定位问题:
- 给容器添加
outline: 2px solid red可视化边界 - 使用浏览器DevTools的Flexbox/Grid覆盖层查看轨道
- 检查是否有隐式网格导致意外行为
- 使用
grid-auto-flow: dense填补网格空洞
🎯 练习任务
- 1 用Flex实现一个粘性页脚布局(内容不足时页脚仍在底部)
- 2 用Grid实现一个包含侧边栏的可折叠后台布局
- 3 实现auto-fit与auto-fill的区别演示
- 4 创建一个CSS Grid的圣杯布局,要求响应式适配移动端
🏆 成就解锁
布局大师 — 灵活运用Flex和Grid构建任何复杂的现代网页布局