DevToolBox免费
博客

CSS Grid 精通:2026年完整指南与实战示例

14 分钟作者 DevToolBox

CSS Grid 是 CSS 中有史以来最强大的布局系统。虽然 Flexbox 处理一维布局(行或列),Grid 同时处理二维布局(行和列)。2026 年,Grid Level 2 的子网格功能已在所有主流浏览器中完全支持。

Grid 基础:列、行和放置

Grid 创建一个二维坐标系。通过使用行号、跨度值或命名区域来指定项目在网格中的位置来放置项目。

/* CSS Grid fundamentals */
.grid-container {
    display: grid;

    /* Define columns */
    grid-template-columns: 200px 1fr 1fr;        /* fixed + flexible */
    grid-template-columns: repeat(3, 1fr);        /* 3 equal columns */
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); /* responsive */

    /* Define rows */
    grid-template-rows: auto 1fr auto;            /* header, content, footer */

    /* Gaps */
    gap: 1rem;            /* both row and column gap */
    row-gap: 0.5rem;
    column-gap: 1.5rem;

    /* Alignment */
    justify-items: stretch;   /* horizontal alignment of cells */
    align-items: start;       /* vertical alignment of cells */
    justify-content: center;  /* horizontal alignment of the grid */
    align-content: center;    /* vertical alignment of the grid */
}

/* Place items */
.item {
    grid-column: 1 / 3;      /* span from column 1 to 3 */
    grid-row: 1 / 2;
    grid-column: span 2;      /* span 2 columns */
    grid-area: 1 / 1 / 3 / 3; /* row-start / col-start / row-end / col-end */
}

grid-template-areas:可视化布局定义

grid-template-areas 允许使用 ASCII 艺术可视化地定义布局。每个字符串代表一行;重复的名称创建跨区域。点(.)创建空单元格。

/* grid-template-areas: name regions visually */
.page-layout {
    display: grid;
    grid-template-areas:
        "header  header  header"
        "sidebar main    main"
        "sidebar aside   aside"
        "footer  footer  footer";
    grid-template-columns: 250px 1fr 300px;
    grid-template-rows: 60px 1fr auto 80px;
    min-height: 100vh;
    gap: 1rem;
}

.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.aside   { grid-area: aside; }
.footer  { grid-area: footer; }

/* Responsive: stack on mobile */
@media (max-width: 768px) {
    .page-layout {
        grid-template-areas:
            "header"
            "main"
            "aside"
            "sidebar"
            "footer";
        grid-template-columns: 1fr;
        grid-template-rows: auto;
    }
}

auto-fill vs auto-fit:无媒体查询的响应式布局

auto-fill 和 auto-fit 配合 minmax() 可以在没有任何媒体查询的情况下创建响应式网格。区别:auto-fill 保留空轨道;auto-fit 折叠它们。

/* auto-fill vs auto-fit — the most important Grid distinction */

/* auto-fill: creates as many columns as possible, even if empty */
.gallery-fill {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 1rem;
}
/* Result: always fills the row with tracks, even with empty ones */

/* auto-fit: collapses empty tracks, stretches filled items */
.gallery-fit {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1rem;
}
/* Result: items expand to fill available space */

/* Practical: responsive card grid (no media queries!) */
.card-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(min(300px, 100%), 1fr));
    gap: 1.5rem;
}
/* min(300px, 100%) prevents overflow on very small screens */

minmax() 和内在大小调整

minmax(min, max) 设置网格轨道的最小和最大尺寸。结合 auto-fill 和 min(),创建能自然适应任何内容和视口的布局。

/* minmax() — set minimum and maximum track size */

/* Card layout: minimum 250px, maximum 1fr */
.cards {
    display: grid;
    grid-template-columns: repeat(3, minmax(250px, 1fr));
}

/* Intrinsic sizing with min-content / max-content */
.table-grid {
    display: grid;
    grid-template-columns: max-content 1fr max-content;
    /* First and last columns size to content, middle fills rest */
}

/* fit-content() — like minmax(auto, max-content) but capped */
.nav {
    display: grid;
    grid-template-columns: fit-content(200px) 1fr fit-content(200px);
}

/* Dense packing: fill holes left by spanning items */
.masonry-like {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
    grid-auto-rows: 150px;
    grid-auto-flow: dense; /* fills gaps automatically */
}

.tall-item {
    grid-row: span 2; /* takes 2 rows */
}
.wide-item {
    grid-column: span 2; /* takes 2 columns */
}

子网格:CSS Grid Level 2(2026)

子网格允许嵌套网格参与父网格的轨道定义。这解决了"卡片对齐"问题——单独卡片内的内容无法跨卡片对齐。

/* Subgrid — CSS Grid Level 2, fully supported in 2026 */
/* Allows nested grids to align to parent grid lines */

/* The problem subgrid solves: */
.card-container {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 1rem;
}

/* Without subgrid: each card's internal layout is independent */
/* Card titles and content don't align across cards */

/* With subgrid: */
.card {
    display: grid;
    grid-row: span 3; /* card spans 3 implicit rows */
    grid-template-rows: subgrid; /* inherits parent row tracks */
}
/* Now all cards share the same row grid — titles align! */

.card .card-header { grid-row: 1; }
.card .card-body   { grid-row: 2; }
.card .card-footer { grid-row: 3; }

/* Subgrid for columns too */
.sidebar-layout {
    display: grid;
    grid-template-columns: 1fr 3fr;
}

.main-content {
    display: grid;
    grid-column: 2;
    grid-template-columns: subgrid; /* aligns to parent columns */
}

/* Browser support: Chrome 117+, Firefox 71+, Safari 16+ — all major browsers */

Grid 动画和过渡

现代浏览器支持对 grid-template-columns 和 grid-template-rows 进行过渡。这实现了侧边栏平滑展开和纯 CSS 手风琴动画。

/* Grid transitions and animation */

/* Animate grid column width on hover */
.sidebar-layout {
    display: grid;
    grid-template-columns: 250px 1fr;
    transition: grid-template-columns 0.3s ease;
}

.sidebar-layout:has(.sidebar:hover) {
    grid-template-columns: 350px 1fr; /* expand on hover */
}

/* CSS-only accordion with Grid */
.accordion-item {
    display: grid;
    grid-template-rows: auto 0fr; /* collapsed: 0 fraction */
    transition: grid-template-rows 0.3s ease;
    overflow: hidden;
}

.accordion-item.open {
    grid-template-rows: auto 1fr; /* expanded: 1 fraction */
}

.accordion-content {
    min-height: 0; /* required for 0fr to work */
}

CSS Grid vs Flexbox:何时使用哪个

ScenarioCSS GridFlexbox
Page layout (header/footer/sidebar)PerfectAwkward
Navigation bar itemsWorksPerfect
Card grid (equal columns)PerfectNeeds JS for equal height
Centering contentEasy (place-items)Easy (align/justify)
Vertical list of itemsWorksPerfect
Complex form layoutPerfectComplex
Responsive without breakpointsauto-fill/fitLimited

最佳实践

  • 使用 Grid 进行页面级布局(header/sidebar/main/footer)。使用 Flexbox 进行组件级布局(导航项、按钮组、卡片内容)。
  • 对于响应式卡片网格,优先使用 repeat(auto-fill, minmax()) 而不是固定列数——可以消除大多数断点。
  • 对复杂布局使用 grid-template-areas 命名网格区域。名称作为自文档化的 CSS。
  • 当需要独立网格子元素中的项目对齐时使用子网格——卡片页脚、表格单元格、价格行。
  • gap 现在通用支持(替代 grid-gap)。使用它而不是 margins 来设置网格间距。

常见问题

什么时候应该使用 CSS Grid vs Flexbox?

CSS Grid 擅长控制行和列的二维布局。Flexbox 更适合一维布局:一排导航链接、项目的垂直堆叠或卡片中的内容。许多设计将 Grid 用于宏观布局,将 Flexbox 用于网格单元格内的组件。

grid-template-columns 和 grid-auto-columns 有什么区别?

grid-template-columns 定义你预先指定的显式列。grid-auto-columns 设置隐式创建的列的大小(当项目溢出定义的网格时)。

子网格与嵌套网格有何不同?

嵌套网格创建自己独立的网格坐标系。子网格继承父级的轨道定义,所以子项目与父网格的线对齐。这对于多列卡片布局至关重要。

grid-auto-flow: dense 有什么作用?

默认情况下,当大项目无法放入时,Grid 按顺序放置项目,留下空洞。grid-auto-flow: dense 让浏览器尝试用后面的项目填充这些空洞。

我可以混用 Grid 和 Flexbox 吗?

当然可以。Grid 和 Flexbox 在不同层次工作。典型模式:CSS Grid 用于页面布局,Flexbox 用于标题导航。混合使用是正常且被鼓励的。

相关工具

𝕏 Twitterin LinkedIn
这篇文章有帮助吗?

保持更新

获取每周开发技巧和新工具通知。

无垃圾邮件,随时退订。

试试这些相关工具

🌈CSS Gradient GeneratorCSS Triangle Generator🎨Color Picker Online

相关文章

Tailwind CSS组件模式:2026年用工具类构建可复用UI

2026年高级Tailwind CSS组件模式:设计令牌、复合组件、多态组件,无需CSS-in-JS的设计系统。

React Query 模式 2026:TanStack Query 数据获取、缓存与变更

2026年精通React Query (TanStack Query) 模式:useQuery、useMutation、乐观更新与服务器状态管理。