Flexbox(Flexible Box Layout Module)是 CSS3 引入的**一維佈局模型**,專為解決「容器內項目如何分配空間、對齊、排序」而設計。它由**伸縮容器**與**伸縮項目**組成,透過主軸與側軸雙軸系統控制佈局。
.container {
display: flex; /* 標準語法 */
display: -webkit-flex; /* Safari 6.1+ */
display: -ms-flexbox; /* IE10 */
/* 早期語法已棄用,現代專案可僅保留標準語法 */
}
子元素自動成為伸縮項目(不含 position:absolute、float 的元素)。
.container {
flex-direction: row | row-reverse | column | column-reverse;
/* row(預設):左→右;column:上→下 */
}
.container {
flex-wrap: nowrap | wrap | wrap-reverse;
/* nowrap(預設):單行,項目壓縮;wrap:多行,側軸方向新增行 */
}
.container { flex-flow: row wrap; } /* 等同上述兩行 */
.container {
justify-content:
flex-start | /* 頭部對齊 */
flex-end | /* 尾部對齊 */
center | /* 置中 */
space-between | /* 兩端對齊,項目間等距 */
space-around | /* 項目兩側等距,邊緣半距 */
space-evenly; /* 所有間距相等(現代瀏覽器) */
}
.container {
align-items:
stretch | /* 預設:拉伸填滿側軸高度 */
flex-start | /* 側軸起點 */
flex-end | /* 側軸終點 */
center | /* 側軸置中 */
baseline; /* 文字基線對齊 */
}
.container {
align-content:
stretch | flex-start | flex-end | center | space-between | space-around;
/* 作用於「伸縮行」整體,非單一項目 */
}
.item { order: 0; /* 預設 0,數值越小越前 */ }
.item { flex-grow: 1; /* 剩餘空間按比例分配 */ }
.item { flex-shrink: 1; /* 空間不足時按比例縮小,0=不縮小 */ }
.item { flex-basis: auto | 200px | 30%; /* 分配前的初始主軸尺寸 */ }
.item {
flex: 1; /* 等同 1 1 0% - 平均分配剩餘空間 */
flex: 0 0 auto; /* 不縮放,按內容/width 決定尺寸 */
flex: 0 0 200px; /* 固定 200px */
flex: 2 1 100px; /* 基準100px,放大比2,縮小比1 */
}
.item-special { align-self: center; }
.container {
display: flex;
min-height: 100vh;
}
.main { flex: 1; order: 1; } /* 主內容佔滿剩餘 */
.aside-left { width: 200px; order: 0; }
.aside-right { width: 200px; order: 2; }
@media (max-width: 768px) {
.container { flex-direction: column; }
.aside-left, .aside-right { width: 100%; order: initial; }
}
.nav { display: flex; align-items: center; justify-content: space-between; }
.nav__brand { order: 1; }
.nav__menu { order: 2; flex: 1; display: flex; justify-content: center; }
.nav__user { order: 3; }
.card { display: flex; flex-direction: column; height: 100%; }
.card__body { flex: 1; display: flex; flex-direction: column; justify-content: space-between; }
.center { display: flex; align-items: center; justify-content: center; }
| 現象 | 原因 | 解決 |
|---|---|---|
| 圖片/影片被壓扁 | 預設 align-items: stretch 拉伸 | 容器加 align-items: center 或項目加 align-self: center |
| 文字不換行撐破容器 | 預設 min-width: auto 受內容撐大 | 項目加 min-width: 0 或 overflow: hidden + text-overflow: ellipsis |
| flex: 1 不生效 | 父容器無主軸剩餘空間(未設寬/高) | 父容器給定主軸尺寸或 flex: 1 1 0% 強制分配 |
| margin: auto 失效 | Flex 容器下 margin 參與空間分配 | 善用 margin-left: auto 推擠項目至右側 |
現代專案:僅寫標準語法,交由 Autoprefixer(PostCSS 插件)根據 browserslist 自動補全。
舊專案需手動維護時,參考 Can I Use 表格。
Flexbox 將一維佈局問題標準化,取代 float/inline-block/table 等 Hack 手段。掌握「容器六屬性 + 項目六屬性」核心體系,配合 flex 簡寫與 gap 間距(現代瀏覽器支援),即可構建 90% 以上的 UI 佈局需求。配合 Grid(二維佈局)形成「Flex 排列、Grid 佈局」雙劍合璧的現代 CSS 佈局體系。