📚 现代前端开发 目录
阶段1:Web基础
第 2 / 35 课

CSS3布局:Flex与Grid

现代CSS布局的双子星

📖 核心概念

💻 代码实现

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经常会遇到一些让人困惑的问题。以下是最常见的几个场景及其解决方案:

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;
}
/* 所有卡片的标题、内容、操作行自动对齐 */

布局调试技巧

当布局不符合预期时,可以使用以下方法快速定位问题:

🎯 练习任务

🏆 成就解锁
布局大师 — 灵活运用Flex和Grid构建任何复杂的现代网页布局