CSS Flex Box Chapter6.

material from: freeCodeCampCSS Tools: Reset CSS

Use the flex Shorthand Property

前面我們依序介紹了 flex items 的相關設定,即 flex-basis、flex-shrink、flex-grow,那有沒有簡寫這些設定的方式呢? 有的,我們可以在 flex items 的 CSS 設定中,直接透過 flex 一次就將值賦予完畢。

flex

flex 這個 property 必須要被賦予3個屬性值,按照指定順序是 flex-grow、flex-shrink、flex-basis。

  • initial
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<style>
...
#box-1 {
background-color: dodgerblue;
flex: 2 2 150px;
height: 200px;
}

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


Use the order Property to Rearrange Items

從段落標題應該可以知道,我們這次要來指定 flex items 在 flex container 裡的順序啦~

order

我們僅需要在每個 flex items 的 CSS 裡指定 order 的屬性值即可,像是order:1;就是指定這個 flex item 在 flex container 裡排在第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;

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>

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

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

透過設定 order 讓 flex items 的排列順序顛倒過來。


Use the align-self Property

align-self 是 flex items 的最後1個 property,它的作用與 flex container 的 align-items 相同,只是它可以個別指定 flex items 的對齊方式,而不是像 align-items 一次指定完所有 flex items 的對齊方式。

align-self

可以給予的值與 align-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
24
<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>

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

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

藍色在 cross axis 上置中對齊,紅色則在 cross axis 上靠下對齊。

恭喜你,到這邊關於 flex box 的介紹就結束了~

分享到