flex#5 justify-content

定義

justify-content會沿著main-axis對齊

快速複習

  • 【預設】flex-direction: row,main-axis為由左至右→→→
  • flex-direction: column,main-axis為由上至下↓↓↓

main-axis為由左至右的情況下(Default)

justify-content: flex-start (default)

items會擠在左邊

.container
  display: flex
  border: 10px solid mistyrose
  justify-content: flex-start
1
2
3
4
5
6
7
8
9
10

justify-content: flex-end

items會擠在右邊

.container
  display: flex
  border: 10px solid mistyrose
  justify-content: flex-end
1
2
3
4
5
6
7
8
9
10

justify-content: center

items會擠中間

.container
  display: flex
  border: 10px solid mistyrose
  justify-content: center
1
2
3
4
5
6
7
8
9
10

justify-content: space-between

第1個item擠在左邊,最後1個item擠在右邊,中間的items均分

.container
  display: flex
  border: 10px solid mistyrose
  justify-content: space-between
1
2
3
4
5
6
7
8
9
10

justify-content: space-around

手法近似於每個item得到一樣的margin-left跟margin-right。
由於第2-9個item的兩邊會重疊鄰居的margin,所以空隙為2倍。
第1個與第10個item的margin沒有鄰居加持,所以與邊界的空隙只有1倍。

.container
  display: flex
  border: 10px solid mistyrose
  justify-content: space-around
1
2
3
4
5
6
7
8
9
10

main-axis為由上至下的情況下(flex-direction: column)

2個注意事項

  • 需要指定min-height
  • 每個item不能給太高(加總高須低於min-height)

justify-content: flex-start

items都擠在上方

.box
  color: white
  font-size: 20px
  text-align: center
  text-shadow: 4px 4px 0 rgba(0, 0, 0, 0.1)
  padding: 10px

.container
  display: flex
  border: 10px solid mistyrose
  flex-direction: column
  min-height: 700px
  justify-content: flex-start
1
2
3
4
5
6
7
8
9
10

justify-content: flex-end

items都擠在下方

.container
  display: flex
  border: 10px solid mistyrose
  flex-direction: column
  min-height: 700px
  justify-content: flex-end
1
2
3
4
5
6
7
8
9
10

justify-content: center

items都擠在中間(狀似孤島)

.container
  display: flex
  border: 10px solid mistyrose
  flex-direction: column
  min-height: 700px
  justify-content: center
1
2
3
4
5
6
7
8
9
10

justify-content: space-between

首尾貼緊上下的均分

.container
  display: flex
  border: 10px solid mistyrose
  flex-direction: column
  min-height: 700px
  justify-content: space-between
1
2
3
4
5
6
7
8
9
10

justify-content: space-around

上下等距的均分

.container
  display: flex
  border: 10px solid mistyrose
  flex-direction: column
  min-height: 700px
  justify-content: space-around
1
2
3
4
5
6
7
8
9
10