Contents

[CSS]flex筆記

CSS Flexbox 是現代 CSS 排版的核心技術,解決了過去用 float 排版的諸多問題。以下整理 Flexbox 的常用屬性和實用範例。

啟用 Flex 容器

1
2
3
.container {
  display: flex;
}

設定 display: flex 後,直接子元素自動成為 flex 子項目(flex items)。

主軸方向(flex-direction)

1
2
3
4
5
6
.container {
  flex-direction: row;            /* 預設:水平從左到右 */
  flex-direction: row-reverse;    /* 水平從右到左 */
  flex-direction: column;         /* 垂直從上到下 */
  flex-direction: column-reverse; /* 垂直從下到上 */
}

主軸對齊(justify-content)

控制子元素在主軸方向的排列方式:

1
2
3
4
5
6
7
8
.container {
  justify-content: flex-start;    /* 靠左(預設) */
  justify-content: flex-end;      /* 靠右 */
  justify-content: center;        /* 置中 */
  justify-content: space-between; /* 兩端對齊,間距均分 */
  justify-content: space-around;  /* 每個元素周圍間距相等 */
  justify-content: space-evenly;  /* 所有間距完全相等 */
}

交叉軸對齊(align-items)

控制子元素在交叉軸(垂直方向)的對齊:

1
2
3
4
5
6
7
.container {
  align-items: stretch;     /* 拉伸填滿(預設) */
  align-items: flex-start;  /* 靠上 */
  align-items: flex-end;    /* 靠下 */
  align-items: center;      /* 垂直置中 */
  align-items: baseline;    /* 文字基線對齊 */
}

換行(flex-wrap)

預設情況下 flex 子元素不換行,擠在同一行:

1
2
3
4
5
.container {
  flex-wrap: nowrap;        /* 不換行(預設) */
  flex-wrap: wrap;          /* 自動換行 */
  flex-wrap: wrap-reverse;  /* 反向換行 */
}

子元素彈性(flex)

flexflex-growflex-shrinkflex-basis 的縮寫:

1
2
3
4
.item {
  flex: 1;      /* 等比例分配剩餘空間 */
  flex: 0 0 200px; /* 固定寬度 200px,不伸縮 */
}

常見實用範例

水平垂直置中

1
2
3
4
5
6
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 300px;
}

導航列(左 Logo,右選單)

1
2
3
4
5
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

等寬卡片排列

1
2
3
4
5
6
7
8
9
.card-container {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.card {
  flex: 1 1 300px; /* 最小 300px,可伸縮 */
}

參考資料