Flexbox 彈性佈局
在容器上設 display: flex,只有一層直接子元素變成 flex item。先決定主軸方向,再用對齊與 flex 分配空間。
啟用
預設 flex-direction: row,子元素由左到右、高度被 stretch 拉齊。
容器屬性(Container)
flex-direction
| 值 | 主軸 |
|---|---|
row |
左 → 右(預設) |
row-reverse |
右 → 左 |
column |
上 → 下 |
column-reverse |
下 → 上 |
交叉軸永遠垂直於主軸:row 時交叉軸是垂直方向。
justify-content(主軸)
| 值 | 效果 |
|---|---|
flex-start / start |
靠主軸起點 |
center |
置中 |
flex-end / end |
靠終點 |
space-between |
兩端貼齊,中間均分 |
space-around |
每項左右有半份空隙 |
space-evenly |
空隙完全相等 |
align-items(交叉軸)
| 值 | 效果 |
|---|---|
stretch |
預設,拉滿交叉軸 |
flex-start / start |
靠交叉軸起點 |
center |
置中 |
flex-end / end |
靠終點 |
baseline |
文字基線對齊 |
單顆 item 可用 align-self 覆寫。
flex-wrap
預設 nowrap 會把子元素擠在一行。wrap 後,多出來的列再用 align-content 分配(只有多行時才有感)。
項目屬性(Flex items)
flex 是 flex-grow、flex-shrink、flex-basis 的縮寫。
| 寫法 | 意義 |
|---|---|
flex: 1 |
1 1 0:均分空間 |
flex: auto |
1 1 auto:依內容,再分配剩餘 |
flex: none |
0 0 auto:完全依內容 |
width 與 flex-basis
在主軸是水平時,flex-basis 優先於 width(除非 basis 是 auto)。想做「最小 12rem、有空就長大」用 flex: 1 1 12rem 搭配 min-width: 0(讓它可以在 Grid/Flex 裡縮小,避免撐破)。
order 可改視覺順序,但會讓鍵盤 Tab 與畫面不一致,無障礙上要小心。
常用版型
整頁置中
側欄 + 主欄
.layout {
display: flex;
flex-wrap: wrap;
gap: 1.5rem;
}
.side { flex: 1 1 14rem; }
.main { flex: 2 1 20rem; }
頁首:logo 左、動作右
.header {
display: flex;
align-items: center;
gap: 1rem;
}
.header .actions { margin-inline-start: auto; }
總結
| 想做的事 | 屬性 |
|---|---|
| 改成直排 | flex-direction: column |
| 主軸分配空隙 | justify-content |
| 交叉軸對齊 | align-items / align-self |
| 自動換行 | flex-wrap: wrap + gap |
| 搶剩餘寬度 | flex: 1 並視情況 min-width: 0 |
二維版面請接 Grid。