跳轉到

建立 2025-02-25 更新 2026-09-11

Flexbox 彈性佈局

在容器上設 display: flex只有一層直接子元素變成 flex item。先決定主軸方向,再用對齊與 flex 分配空間。

啟用

<div class="toolbar">
  <button>1</button>
  <button>2</button>
  <button>3</button>
</div>
.toolbar {
  display: flex;
  gap: 0.5rem;
}

預設 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 分配(只有多行時才有感)。

.chips {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

項目屬性(Flex items)

flexflex-growflex-shrinkflex-basis 的縮寫。

.search { flex: 1 1 12rem; } /* 可長大、可縮小,基準 12rem */
.logo { flex: 0 0 auto; }    /* 不搶剩餘空間 */
寫法 意義
flex: 1 1 1 0:均分空間
flex: auto 1 1 auto:依內容,再分配剩餘
flex: none 0 0 auto:完全依內容

widthflex-basis

在主軸是水平時,flex-basis 優先於 width(除非 basis 是 auto)。想做「最小 12rem、有空就長大」用 flex: 1 1 12rem 搭配 min-width: 0(讓它可以在 Grid/Flex 裡縮小,避免撐破)。

order 可改視覺順序,但會讓鍵盤 Tab 與畫面不一致,無障礙上要小心。

常用版型

整頁置中

.center {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100dvh;
}

側欄 + 主欄

.layout {
  display: flex;
  flex-wrap: wrap;
  gap: 1.5rem;
}
.side { flex: 1 1 14rem; }
.main { flex: 2 1 20rem; }
.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