🎯 CSS Flex 佈局完整教學
1. 基本 Flex 容器
2. flex-direction(排列方向)
row(預設):水平排列
flex-direction: row;
column:垂直排列
flex-direction: column;
row-reverse:水平反向排列
flex-direction: row-reverse;
3. justify-content(主軸對齊)
flex-start:起點對齊
justify-content: flex-start;
center:居中對齊
justify-content: center;
space-between:兩端對齊,中間等距
justify-content: space-between;
space-around:每個項目兩側間距相等
justify-content: space-around;
4. align-items(交叉軸對齊)
center:交叉軸居中
align-items: center;
stretch:伸展填滿容器
align-items: stretch;
5. flex 屬性(彈性比例)
.item1 { flex: 1; } /* 佔 1 份 */
.item2 { flex: 2; } /* 佔 2 份 */
.item3 { flex: 3; } /* 佔 3 份 */
6. 實際應用範例
📍 導航列佈局
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
}
📍 卡片佈局
.card-layout {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card { flex: 1; min-width: 250px; }
📍 側邊欄佈局
.sidebar-layout { display: flex; gap: 20px; }
.sidebar { flex: 0 0 200px; } /* 固定寬度 */
.main-content { flex: 1; } /* 剩餘空間 */
📍 完美置中
.center {
display: flex;
justify-content: center;
align-items: center;
}
我在容器的正中央!
🎯 重要提醒
- ✅ display: flex 是啟用 Flex 佈局的關鍵
- ✅ justify-content 控制主軸方向的對齊
- ✅ align-items 控制交叉軸方向的對齊
- ✅ flex 屬性控制項目的彈性比例
- ✅ gap 可以簡單設定項目間距