iT邦幫忙

2025 iThome 鐵人賽

DAY 29
0
Modern Web

程式煉金術:Bug退散!前端驅魔記系列 第 29

Day 29 - Grid 進階:自動排列與範圍控制

  • 分享至 

  • xImage
  •  

學習目標

  • 了解 auto-fitauto-fill 的差異
  • 學會使用 minmax() 實現彈性網格
  • 練習 repeat() 自動生成欄位
  • 使用 grid-area 命名區塊,提高可讀性
  • 嘗試結合 RWD 思維建立自適應版面

常見錯誤與修正

  • ❌ 每個欄位手動定義 → ✅ 使用 repeat() 自動化產生
  • ❌ 固定寬度導致破版 → ✅ 使用 minmax() 寬度範圍控制
  • ❌ 分不清 auto-fitauto-fill → ✅ fit 會自動壓縮、fill 會保留空格
  • ❌ 網格命名太亂 → ✅ 使用 grid-template-areas 統一規劃

今日小挑戰(可交付)

  • [ ] 使用 repeat(auto-fit, minmax()) 製作自動調整的卡片排版
  • [ ] 練習設定 grid-template-areas 來控制區域
  • [ ] 嘗試製作一個三欄 RWD 網格(小螢幕變單欄)
  • [ ] 測試 auto-fillauto-fit 的不同效果
  • [ ] 為每個區域命名,並用 CSS 指定位置
body {
  font-family: "Microsoft JhengHei", sans-serif;
  background: #f4f6f8;
  margin: 40px;
}

h1 {
  text-align: center;
  color: #34495e;
  margin-bottom: 20px;
}

.grid-container {
  display: grid;
  grid-template-areas:
    "header header"
    "sidebar content"
    "footer footer";
  grid-template-columns: 1fr 3fr;
  gap: 10px;
}

.item {
  background: #3498db;
  color: white;
  padding: 20px;
  border-radius: 8px;
  font-weight: bold;
  text-align: center;
}

.header { grid-area: header; }
.sidebar { grid-area: sidebar; background: #9b59b6; }
.content { grid-area: content; background: #1abc9c; }
.footer { grid-area: footer; background: #2ecc71; }

常見錯誤與修正

  • ❌ 每個欄位手動定義 → ✅ 使用 repeat() 自動化產生
  • ❌ 固定寬度導致破版 → ✅ 使用 minmax() 寬度範圍控制
  • ❌ 分不清 auto-fitauto-fill → ✅ fit 會自動壓縮、fill 會保留空格
  • ❌ 網格命名太亂 → ✅ 使用 grid-template-areas 統一規劃

今日小挑戰(可交付)

  • [ ] 使用 repeat(auto-fit, minmax()) 製作自動調整的卡片排版
  • [ ] 練習設定 grid-template-areas 來控制區域
  • [ ] 嘗試製作一個三欄 RWD 網格(小螢幕變單欄)
  • [ ] 測試 auto-fillauto-fit 的不同效果
  • [ ] 為每個區域命名,並用 CSS 指定位置

DAY29 心得

今天的 Grid 進階課 讓我真正體會到它的強大。以前做 RWD 時,總要靠 Media Query 一一調整區塊,現在用 auto-fit 搭配 minmax(),就能自動伸縮,排版變得靈活又整潔。

我特別喜歡 grid-template-areas 的語法,像在畫設計稿一樣,只要命名好區域,就能清楚知道每個區塊的位置。這讓整個版面結構更直覺,也更容易維護。

相較於 Flexbox 注重「內容驅動」,Grid 更像是「版面驅動」的思維。它讓我第一次覺得排版是一種規劃的藝術,而不只是堆元素。

到這裡我終於明白,HTML 是骨架,CSS 是靈魂。
學會 Grid,就像掌握了排版世界的地圖。


上一篇
Day 28 - Grid 布局入門
系列文
程式煉金術:Bug退散!前端驅魔記29
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言