CSS 彈性盒子 Flexbox
Flexbox 基本概念
主軸與交叉軸
Flexbox 佈局基於兩個軸線:
- 主軸 (Main Axis): 由
flex-direction定義的軸線,flex items 沿著主軸排列 - 交叉軸 (Cross Axis): 垂直於主軸的軸線
flex-direction: row (預設)
┌─────────────────────────────────┐
│ ↓ Cross Axis │
│ ┌───┐ ┌───┐ ┌───┐ │
│ │ 1 │ │ 2 │ │ 3 │ → Main Axis │
│ └───┘ └───┘ └───┘ │
└─────────────────────────────────┘
flex-direction: column
┌─────────────────┐
│ → Cross Axis │
│ ┌───┐ │
│ │ 1 │ ↓ │
│ └───┘ │
│ ┌───┐ Main │
│ │ 2 │ Axis │
│ └───┘ │
│ ┌───┐ │
│ │ 3 │ │
│ └───┘ │
└─────────────────┘
容器與項目
- Flex Container: 設定
display: flex或display: inline-flex的父元素 - Flex Items: Flex Container 的直接子元素
Flex Container 屬性
1. display
啟用 Flexbox 佈局:
.container {
display: flex; /* 或 inline-flex */
}
2. flex-direction
定義主軸方向,決定 flex items 的排列方向:
.container {
flex-direction: row; /* 預設值,水平從左到右 */
flex-direction: row-reverse; /* 水平從右到左 */
flex-direction: column; /* 垂直從上到下 */
flex-direction: column-reverse; /* 垂直從下到上 */
}
flex-direction 範例
觀察不同 flex-direction 值如何改變項目排列方向
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
align-content: stretch;
flex-wrap: nowrap;
gap: 10px;1
2
3
4
3. justify-content
定義 flex items 在主軸上的對齊方式:
.container {
justify-content: flex-start; /* 預設值,靠主軸起點對齊 */
justify-content: flex-end; /* 靠主軸終點對齊 */
justify-content: center; /* 置中對齊 */
justify-content: space-between; /* 兩端對齊,項目間距相等 */
justify-content: space-around; /* 項目兩側間距相等 */
justify-content: space-evenly; /* 所有間距完全相等 */
}
間距示意
space-between: [1]────[2]────[3]
space-around: ──[1]────[2]────[3]──
space-evenly: ───[1]───[2]───[3]───
justify-content 範例
調整 justify-content 觀察主軸上的對齊效果
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
align-content: stretch;
flex-wrap: nowrap;
gap: 10px;1
2
3
4