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#响应式