CSS Flex Box Chapter5.

material from: freeCodeCampCSS Tools: Reset CSS

Use the flex-grow Property to Expand Items

之前我們在 flex items 上設定 flex-shrink 指定視窗縮小時,flex items 各自要縮小的比例,那我們要如何指定視窗放大時,flex items 各自的放大比例呢? 答案是可以在 flex items 的 CSS 設定裡加上 flex-grow。

flex-grow

用法和 flex-shrink 相同,在 flex-items 設定各自的 flex-grow 並以數字大小決定哪個 flex item 要在視窗變大時,變得比其他的 flex items 還要大。

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

#box-1 {
background-color: dodgerblue;
height: 200px;
width: 200px;
}

#box-2 {
background-color: orangered;
height: 200px;
width: 200px;
}
</style>

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

視窗放大時:

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

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

視窗放大時:
(紅色比藍色還要寬)

要注意的地方是當有明確規範 flex items 的 width (ex. 200px) 時,如果有在 flex items 的 CSS 上設定 flex-grow,則 flex items 會無視原本指定的 width,轉而盡量填滿整個 flex container。


Use the flex-basis Property to Set the Initial Size of an Item

在運用 flex box 時,我們通常不會直接透過 width 來指定寬度,而是使用 flex-basis 指定在視窗未 shrink 或 grow 時的初始寬度。

跟 flex-shrink 與 flex-grow 不同的點在於 flex-basis 不能只單純賦予數值,同時還要給予單位才行。

flex-basis

  • inital
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<style>
#box-container {
display: flex;
height: 500px;
}

#box-1 {
background-color: dodgerblue;
height: 200px;
}

#box-2 {
background-color: orangered;
height: 200px;
}
</style>

<div id="box-container">
<div id="box-1"></div>
<div id="box-2"></div>
</div>
  • 設定 flex-basis
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<style>
...
#box-1 {
background-color: dodgerblue;
height: 200px;
flex-basis: 150px;
}

#box-2 {
background-color: orangered;
height: 200px;
flex-basis: 250px;
}
</style>
...

分享到