display: flex
、flex-direction
、justify-content
、align-items
flex: 1
)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;
}
display: flex
,不知道主軸方向 → ✅ 用 flex-direction
控制 row/columnjustify-content
+ align-items
輕鬆置中flex: 1
自動分配空間gap
,避免用 margin 撐開justify-content
的各種值(center, space-between, space-around)gap
控制間距,不用 margin今天終於進入到 Flexbox,真的感覺到 CSS 的現代力量。過去用 float 或 position 排版的痛苦,現在用 display: flex
就能輕鬆解決。
我覺得 Flexbox 最直覺的就是「主軸 vs 交叉軸」的觀念,搞清楚方向之後,用 justify-content
和 align-items
就能快速調整位置。尤其是「水平 + 垂直置中」這種老問題,在 Flexbox 裡只要兩行就能搞定。
雖然今天只學到基礎,但我已經能感受到它取代 float 的優勢。接下來應該會更深入 grid 與響應式設計,讓排版變得更靈活。