← HTML / CSS Course

CSS CORE · 49

Flexbox / Grid:先選 Layout Model,再調 Property

Flex 與 Grid 不是兩套要背完的 property 清單。先判斷問題主要是一維 flow 還是二維 tracks,再選 layout model。

Learning outcomes

1. Flex:沿主要 axis 分配空間

.toolbar {
  display: flex;
  align-items: center;
  gap: .75rem;
}

.search {
  flex: 1;
}

Main axis 由 flex-direction 決定;justify-content 通常沿 main axis,align-items 沿 cross axis。

2. Wrap 讓一維 layout 有第二行

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: .5rem;
}

這仍主要是一維 flow,不等於 Grid 的二維 track model。

3. Grid:定義 rows/columns tracks

.modules {
  display: grid;
  grid-template-columns:
    repeat(3, 1fr);
  gap: 1rem;
}

4. Responsive grid 不一定先需要 media query

.modules {
  display: grid;
  grid-template-columns:
    repeat(
      auto-fit,
      minmax(14rem, 1fr)
    );
  gap: 1rem;
}

Browser 可以依 available space 自動決定欄數。

5. 先讓 normal flow 工作

不要一開始就 absolute position 每張卡片。Normal flow + Flex/Grid 讓內容高度與 viewport 變動時更有韌性。

Project checkpoint:Course Profile v6

.course-header {
  display: flex;
  justify-content:
    space-between;
  align-items: center;
  gap: 1rem;
  flex-wrap: wrap;
}

.modules {
  display: grid;
  grid-template-columns:
    repeat(
      auto-fit,
      minmax(15rem, 1fr)
    );
  gap: 1rem;
}

Debug evidence:卡片被壓得很窄

  1. container 有多少 available width?
  2. grid minmax 的 minimum 是多少?
  3. flex item 是否允許 shrink/wrap?
  4. child 有沒有不可收縮 fixed width?

Knowledge check

  1. Toolbar 和 card wall 各更像哪種問題?
  2. 1fr 在 Grid 裡代表什麼概念?
  3. 把三欄固定 grid 改成 auto-fit/minmax。
  4. 用 DevTools Layout panel 觀察 tracks / gaps。