CSS 现代布局实战:Grid、Flexbox 与 Container Queries

前端工程(更新于 2026年5月30日)

布局方案的演进

时代 方案 问题
表格布局 <table> 语义错误、不灵活
浮动布局 float + clearfix 高度塌陷、复杂
定位布局 position: absolute 脱离文档流
Flexbox display: flex 一维布局
CSS Grid display: grid 二维布局
Container Queries @container 组件级响应式

Flexbox:一维布局

适合导航栏、工具卡片行、按钮组等单行/单列排列:

.tool-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 1rem;
}

.tool-card {
  flex: 1 1 280px; /* -grow shrink basis */
  min-width: 0;    /* 防止内容溢出 */
}

常用模式

/* 水平居中 */
.center { display: flex; justify-content: center; align-items: center; }

/* 两端对齐 */
.navbar { display: flex; justify-content: space-between; align-items: center; }

/* 垂直堆叠 */
.sidebar { display: flex; flex-direction: column; gap: 0.5rem; }

工具库首页的工具卡片网格使用 flex-wrap + flex-basis: 280px 实现自适应列数。


CSS Grid:二维布局

适合页面整体结构、工具分类页等行列同时控制的场景:

.page-layout {
  display: grid;
  grid-template-columns: 240px 1fr;
  grid-template-rows: auto 1fr auto;
  min-height: 100vh;
}

.sidebar  { grid-row: 1 / -1; grid-column: 1; }
.header   { grid-column: 2; }
.main     { grid-column: 2; overflow: auto; }
.footer   { grid-column: 2; }

自适应网格

.tool-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 1rem;
}

auto-fill + minmax 让网格自动计算列数——窗口宽则 4 列,窄则 2 列,无需媒体查询。


Container Queries:组件级响应式

传统媒体查询基于视口宽度,Container Queries 基于父容器宽度

.tool-card-container {
  container-type: inline-size;
}

@container (max-width: 400px) {
  .tool-card {
    flex-direction: column;
    padding: 0.75rem;
  }
  .tool-card .icon { display: none; }
}

@container (min-width: 401px) {
  .tool-card {
    flex-direction: row;
    padding: 1.25rem;
  }
}

优势:同一个组件在侧边栏(窄容器)和主内容区(宽容器)中自动适配,无需全局媒体查询。


工具库布局实践

工具页布局

┌──────────────────────────────────┐
│  Header (flex, space-between)    │
├────────┬─────────────────────────┤
│ Side   │  Tool Area (grid)       │
│ nav    │  ┌─────┐ ┌─────┐      │
│ (grid  │  │Input│ │Output│      │
│  1fr)  │  └─────┘ └─────┘      │
│        │  ┌─────────────────┐  │
│        │  │   Action Bar    │  │
│        │  └─────────────────┘  │
├────────┴─────────────────────────┤
│  Footer                          │
└──────────────────────────────────┘

响应式断点

断点 布局变化
< 640px 单列,侧边栏折叠为抽屉
640-1024px 双列工具网格
> 1024px 三列工具网格 + 固定侧边栏

实用 CSS 工具


总结

Flexbox 解决一维排列,Grid 解决二维结构,Container Queries 实现组件级响应式——三者组合覆盖了现代 Web 布局的全部需求。工具库的 UI 正是这套布局体系的实战应用。

本站提供浏览器本地工具,免注册即可试用 →

#CSS#Grid#Flexbox#Container Queries#响应式