← 返回目录

CSS 布局实战:Flex 与 Grid 双布局体系

入门 · 第 3 篇 ·

Flexbox:一维布局之王

Flexbox 擅长处理行或列方向上的元素排列。核心概念:主轴(main axis)和交叉轴(cross axis)。

容器属性

.flex-container {
  display: flex;
  flex-direction: row;          /* 默认水平 */
  flex-direction: column;       /* 垂直 */
  justify-content: center;      /* 主轴对齐 */
  justify-content: space-between;
  align-items: center;          /* 交叉轴对齐 */
  flex-wrap: wrap;              /* 换行 */
  gap: 16px;                    /* 间距 */
}

项目属性

.flex-item {
  flex: 1;            /* 等分 */
  flex: 0 0 200px;    /* 固定宽度 */
  align-self: flex-end; /* 单独对齐 */
}

实战:圣杯布局

<style>
.holy-grail {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}
.holy-grail > main {
  display: flex;
  flex: 1;
}
.holy-grail .left { width: 200px; }
.holy-grail .center { flex: 1; }
.holy-grail .right { width: 200px; }
</style>

<div class="holy-grail">
  <header>头部</header>
  <main>
    <aside class="left">左侧栏</aside>
    <div class="center">主内容</div>
    <aside class="right">右侧栏</aside>
  </main>
  <footer>底部</footer>
</div>

CSS Grid:二维布局利器

Grid 同时处理行和列,适合页面整体布局和复杂的网格结构。

容器属性

.grid-container {
  display: grid;
  grid-template-columns: 200px 1fr 200px;
  grid-template-columns: repeat(3, 1fr);
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  grid-template-rows: auto 1fr auto;
  gap: 16px;
}

项目定位

.grid-item {
  grid-column: 1 / 3;    /* 跨两列 */
  grid-row: span 2;      /* 跨两行 */
  justify-self: center;
  align-self: center;
}

实战:瀑布流卡片

.masonry {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}
.masonry .card { border: 1px solid #eee; border-radius: 8px; padding: 1rem; }

Flex vs Grid:如何选择

经典布局技巧

水平垂直居中

/* Flex 方案 */
.center-flex {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* Grid 方案 */
.center-grid {
  display: grid;
  place-items: center;
}

等高列

/* Grid 默认等高 */
.equal-height {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
}

/* Flex 配合 stretch(默认值) */
.equal-height-flex {
  display: flex;
}

粘性页脚

body {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}
main { flex: 1; }
footer { /* 自动推到底部 */ }

小结

Flex 和 Grid 是现代 CSS 布局的两大支柱。Flex 擅长一维排列,Grid 擅长二维网格,两者互补。掌握这两个布局体系,能解决 95% 以上的页面布局问题。

下一篇:JavaScript 基础:变量、函数与控制流