iT邦幫忙

2025 iThome 鐵人賽

DAY 26
0

學習目標

  • 理解 Flexbox 的核心概念:主軸(main axis)與交叉軸(cross axis)
  • 熟悉容器屬性:display: flexflex-directionjustify-contentalign-items
  • 學會讓子元素自動分配空間(flex: 1
  • 用 Flexbox 製作水平/垂直置中版面

body {
  font-family: "Microsoft JhengHei", sans-serif;
  margin: 20px;
  background: #f5f5f5;
}

h1 {
  text-align: center;
  margin-bottom: 20px;
}

.container {
  display: flex;
  margin: 20px auto;
  gap: 10px;
  padding: 10px;
  background: #ecf0f1;
  border-radius: 8px;
}

.row {
  flex-direction: row; /* 預設:水平排列 */
  justify-content: space-around;
  align-items: center;
}

.column {
  flex-direction: column; /* 垂直排列 */
  align-items: flex-start;
}

.item {
  flex: 1;
  padding: 20px;
  background: #3498db;
  color: white;
  text-align: center;
  border-radius: 6px;
}

.center {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  background: #9b59b6;
  color: white;
  border-radius: 8px;
  margin-top: 30px;
}

image

常見錯誤與修正

  • ❌ 只設 display: flex,不知道主軸方向 → ✅ 用 flex-direction 控制 row/column
  • ❌ 用 margin 把元素硬推到中間 → ✅ 用 justify-content + align-items 輕鬆置中
  • ❌ 每個子元素固定寬度 → ✅ 使用 flex: 1 自動分配空間
  • ❌ 忽略間距控制 → ✅ 善用 gap,避免用 margin 撐開

今日小挑戰(可交付)

  • [ ] 嘗試用 Flexbox 建立一個三等分的水平排版
  • [ ] 練習 column 方向,讓區塊垂直排列
  • [ ] 製作一個水平 + 垂直置中的區塊
  • [ ] 測試 justify-content 的各種值(center, space-between, space-around)
  • [ ] 使用 gap 控制間距,不用 margin

DAY26 心得

今天終於進入到 Flexbox,真的感覺到 CSS 的現代力量。過去用 float 或 position 排版的痛苦,現在用 display: flex 就能輕鬆解決。

我覺得 Flexbox 最直覺的就是「主軸 vs 交叉軸」的觀念,搞清楚方向之後,用 justify-contentalign-items 就能快速調整位置。尤其是「水平 + 垂直置中」這種老問題,在 Flexbox 裡只要兩行就能搞定。

雖然今天只學到基礎,但我已經能感受到它取代 float 的優勢。接下來應該會更深入 grid 與響應式設計,讓排版變得更靈活。


上一篇
Day 25 - CSS 浮動與清除
系列文
程式煉金術:Bug退散!前端驅魔記26
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言