CSS Flex Box Chapter1.

material from: freeCodeCampCSS Tools: Reset CSS

Use display: flex to Position Two Boxes

這邊算是 flex box 的初入門,display:flex 宣告父容器要用 flex box 的形式放置網頁元素。

因為下面設定2個box各佔50%寬度的關係而且沒有多寫flex: wrap;,所以在縮放視窗時,沒辦法感受到 flex box 的威力,原則上所有子元素都會被排在同一列上。

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 { #父容器
height: 500px;
display: flex;
}

#box-1 { #子元素
background-color: dodgerblue;
width: 50%; #均分寬度
height: 50%;
}

#box-2 {
background-color: orangered;
width: 50%;
height: 50%;
}
</style>
<div id="box-container">
<div id="box-1"></div>
<div id="box-2"></div>
</div>
  • display: flex;

  • 沒有display: flex;


上面的東西只要再多個flex: wrap;就可以做個簡易的 Image Gallery,flex: wrap;在後面會提到,現在只要知道它可以讓原本"被迫"排在一起的元素,按實際指定的 width 依序排在不同列上。

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
<body>
<div class="box-container">
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
<div class="box5"></div>
<div class="box6"></div>
</div>
</body>
<style>
.box-container{
height: 100%;
display: flex;
flex-wrap: wrap;
}
.box1{
width: 50%;
height: 250px;
background-color: rgb(140, 231, 231);
}
.box2{
width: 50%;
height: 250px;
background-color: rgb(120, 243, 202);
}
.box3{
width: 33.3333%;
height: 250px;
background-color: rgb(65, 136, 136);
}
.box4{
width: 33.3333%;
height: 250px;
background-color: rgb(105, 126, 126);
}
.box5{
width: 33.3333%;
height: 250px;
background-color: rgb(57, 83, 83);
}
.box6{
width: 100%;
height: 250px;
background-color: rgb(9, 160, 160);
}
</style>

  • 加上圖片再調整個別高度就完成啦~
    ps. 現在的長寬比是照我的螢幕尺寸做規劃,其他尺寸的螢幕有可能會跑版。

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
<body>
<div class="box-container">
<div class="box1"><img src="image/thumb1.jpg" width="100%" height="100%"></div>
<div class="box2"><img src="image/thumb2.jpg" width="100%" height="100%"></div>
<div class="box3"><img src="image/thumb3.jpg" width="100%" height="100%"></div>
<div class="box4"><img src="image/thumb4.jpg" width="100%" height="100%"></div>
<div class="box5"><img src="image/thumb5.jpg" width="100%" height="100%"></div>
<div class="box6"><img src="image/thumb6.jpg" width="100%" height="100%"></div>
</div>
</body>
<style>
.box-container{
height: 100%;
display: flex;
flex-wrap: wrap;
}
.box1{
width: 50%;
height: 350px;
background-color: rgb(140, 231, 231);
}
.box2{
width: 50%;
height: 350px;
background-color: rgb(120, 243, 202);
}
.box3{
width: 33.3333%;
height: 250px;
background-color: rgb(65, 136, 136);
}
.box4{
width: 33.3333%;
height: 250px;
background-color: rgb(105, 126, 126);
}
.box5{
width: 33.3333%;
height: 250px;
background-color: rgb(57, 83, 83);
}
.box6{
width: 100%;
height: 650px;
background-color: rgb(9, 160, 160);
}
</style>
分享到