Flex / Grid 版面入門 31–35 節

← 返回首頁

學習目標:掌握 Flex 與 Grid 的核心用法,能排出常見卡片與兩欄版面。

搭配瀏覽器開發者工具(F12)觀看 displaygapjustify/align 等變化。

31. Flex 基本概念:主軸 / 交叉軸

Flex 是一維(單一方向)排版:以主軸排列子元素,另一方向稱交叉軸。

.container {
  display: flex;
  flex-direction: row;
  gap: 8px;
}
.item { padding: 8px 10px; background: #e0e7ff; }
1
2
3
目前:row
小練習:點擊上方按鈕改變屬性,或打開 F12 直接修改樣式,嘗試做出你想要的排列。

32. Flex 容器屬性

了解 flex-wrap、justify-content(主軸對齊)、align-items(交叉軸對齊)。

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  align-items: center;
  gap: 8px;
}
A
B
C
D
E
小練習:點擊上方按鈕改變屬性,或打開 F12 直接修改樣式,嘗試做出你想要的排列。

33. Flex 子項目屬性

掌握 flex(grow/shrink/basis)、order、align-self 等。

.item:nth-child(1) { flex: 1 1 120px; }
.item:nth-child(2) { flex: 2 1 120px; }
.item:nth-child(3) { flex: 1 1 120px; }
1
2(flex:2)
3
小練習:點擊上方按鈕改變屬性,或打開 F12 直接修改樣式,嘗試做出你想要的排列。

34. Grid 基本概念

Grid 是二維格線:同時定義列與欄。

.grid {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-auto-rows: 80px;
  gap: 8px;
}
1
2
3
4
5
6
小練習:點擊上方按鈕改變屬性,或打開 F12 直接修改樣式,嘗試做出你想要的排列。

35. Grid 常用語法與實戰範例

repeat(auto-fit, minmax()) 做自適應卡片,grid-template-areas 快速排大版。

/* 自適應卡片 */
.cards {
  display:grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 12px;
}

/* 區塊版型 */
.layout {
  display:grid;
  grid-template-areas:
    "header header"
    "main   aside"
    "footer footer";
  grid-template-columns: 2fr 1fr;
  gap: 8px;
}
.header { grid-area: header; }
.main   { grid-area: main; }
.aside  { grid-area: aside; }
.footer { grid-area: footer; }
卡 1
卡 2
卡 3
卡 4
卡 5
Header
Main
Aside
Footer
小練習:點擊上方按鈕改變屬性,或打開 F12 直接修改樣式,嘗試做出你想要的排列。

© 戴梅枝 — 完成 31–35 節後,可回到 CSS 30 屬性 複習,或繼續做作品。