面试题之css(四)

Flex 布局

Flex 布局是 CSS3 中的一种布局方式,它通过简化布局的实现过程,极大地增强了 CSS 布局的能力。使用 Flex 布局可以轻松地创建各种复杂的布局。

Flex 容器与项目

  • Flex 容器:设置了 display: flexdisplay: inline-flex 的元素。
  • Flex 项目:容器内部的子元素。
常见的 Flex 属性
容器属性
  1. display:指定为 Flex 容器。

    1
    2
    3
    .container {
    display: flex;
    }
  2. flex-direction:定义主轴方向。

    1
    2
    3
    .container {
    flex-direction: row; /* 默认值,可以是row, row-reverse, column, column-reverse */
    }
  3. justify-content:定义主轴上的对齐方式。

    1
    2
    3
    .container {
    justify-content: center; /* 可以是flex-start, flex-end, center, space-between, space-around, space-evenly */
    }
  4. align-items:定义交叉轴上的对齐方式。

    1
    2
    3
    .container {
    align-items: center; /* 可以是flex-start, flex-end, center, baseline, stretch */
    }
  5. flex-wrap:定义是否换行。

    1
    2
    3
    .container {
    flex-wrap: nowrap; /* 可以是nowrap, wrap, wrap-reverse */
    }
项目属性
  1. flex:指定项目如何分配空间。

    1
    2
    3
    .item {
    flex: 1; /* 可以是flex-grow, flex-shrink, flex-basis的缩写 */
    }
  2. align-self:允许单个项目有不同的对齐方式。

    1
    2
    3
    .item {
    align-self: center; /* 可以是auto, flex-start, flex-end, center, baseline, stretch */
    }

使用 Flex 布局实现居中

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Flex布局居中</title>
<style>
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
border: 1px solid #000;
}
.item {
width: 100px;
height: 100px;
background-color: lightcoral;
}
</style>
</head>
<body>
<div class="container">
<div class="item">居中</div>
</div>
</body>
</html>

使用 Flex 布局实现两栏布局

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Flex布局两栏</title>
<style>
.container {
display: flex;
}
.left,
.right {
flex: 1;
height: 100vh;
}
.left {
background-color: lightblue;
}
.right {
background-color: lightgreen;
}
</style>
</head>
<body>
<div class="container">
<div class="left">左侧栏</div>
<div class="right">右侧栏</div>
</div>
</body>
</html>

使用 Flex 布局实现三栏布局

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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Flex布局三栏</title>
<style>
.container {
display: flex;
}
.left,
.middle,
.right {
flex: 1;
height: 100vh;
}
.left {
background-color: lightblue;
}
.middle {
background-color: lightcoral;
}
.right {
background-color: lightgreen;
}
</style>
</head>
<body>
<div class="container">
<div class="left">左侧栏</div>
<div class="middle">中间栏</div>
<div class="right">右侧栏</div>
</div>
</body>
</html>