CSS Flex Box Chapter4.

material from: freeCodeCampCSS Tools: Reset CSS

Use the flex-wrap Property to Wrap a Row or Column

CSS 的 flexbox 有一個特性會將 flex container 拆分成數個 rows 或 columns。

在預設情況下,flex container 會將所有的 flex items 都放在同一 row 或 column 而不會自動將 flex items 放到下一 row 或 column 做自動換行(無視 flex container 的大小硬擠)。

要讓這些 flex items 換行,我們可以在 flex container 的 CSS 設定中加上 flex-wrap:wrap; 讓 flex items 能落到新的 row 或 column 而不是都擠在一起。

📝 flex-wrap

flex-wrap 能設定的值 : no-wrap (default)、wrapwrap-reverse
不指定 flex-wrap 的話,則預設flex-wrap:wrap;

  • no-wrap (default)

無視 CSS 中的 flex container 和 flex items 的 size 設定,強行把 flex items 全部擠到同一 row 或 column。圖片中的 flex items 都已經不是原本該有的 size,在擠壓過程中已經遭到縮放。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<style>
#box-container {
background: gray;
display: flex;
height: 100%;

}
#box-1 {
background-color: dodgerblue;
width: 25%;
height: 50%;
}

#box-2 {
background-color: orangered;
width: 25%;
height: 50%;
}
#box-3 {
background-color: violet;
width: 25%;
height: 50%;
}
#box-4 {
background-color: yellow;
width: 25%;
height: 50%;
}
#box-5 {
background-color: green;
width: 25%;
height: 50%;
}
#box-6 {
background-color: black;
width: 25%;
height: 50%;
}
</style>

<div id="box-container">
<div id="box-1"></div>
<div id="box-2"></div>
<div id="box-3"></div>
<div id="box-4"></div>
<div id="box-5"></div>
<div id="box-6"></div>
</div>

  • wrap

將理應超出 flex container 但被強行擠在同一 row 或 column 的 flex items,依照實際 size 將排不下的 flex items 排到下一 row 或 column。
flex items 恢復實際上的 size。

1
2
3
4
5
6
7
8
9
10
<style>
#box-container {
background: gray;
display: flex;
height: 100%;
flex-wrap: wrap;
}
...
</style>
...

  • wrap-reverse

與 wrap 排出的 flex items 剛好顛倒。

1
2
3
4
5
6
7
8
9
10
<style>
#box-container {
background: gray;
display: flex;
height: 100%;
flex-wrap: wrap-reverse;
}
...
</style>
...


Use the flex-shrink Property to Shrink Items

如果你有動手玩過 flex box 的話,你會發現視窗縮小的同時,flex items 的大小也會跟著變小,在預設情況下,每個 flex items 的縮小比例都是一樣的,但是我們可以在 flex items 的 CSS 設定裡加上flex-shrink去詳細指定每個 flex items 要縮小的多寡。

flex shrink

default: flex-shrink:1;

  • initial
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<style>
#box-container {
display: flex;
height: 500px;
}
#box-1 {
background-color: dodgerblue;
width: 100%;
height: 200px;

}

#box-2 {
background-color: orangered;
width: 100%;
height: 200px;

}
</style>

<div id="box-container">
<div id="box-1"></div>
<div id="box-2"></div>
</div>

視窗縮小時 :
(紅色跟藍色縮小比例一樣)

  • 有設定不同的 flex-shrink
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<style>
...
#box-1 {
background-color: dodgerblue;
width: 100%;
height: 200px;
flex-shrink: 3;
}

#box-2 {
background-color: orangered;
width: 100%;
height: 200px;
flex-shrink: 1;
}
</style>
...

視窗縮小時 :
(可以看到紅色比藍色還要寬)

分享到