一.flex是什么,为什么要学习flex,以及学习flex的好处

1.响应式布局:适应不同屏幕的大小和设备的布局。
2.内容对齐和居中: 可以轻松地在主轴和交叉轴上对齐和居中元素,而无需使用繁琐的定位和浮动。

二.以下是一些常用的 Flex 布局属性:

1
2
3
4
5
6
7
8
9
flex-direction: 定义了项目的排列方向,可以是 row(水平排列)、column(垂直排列)、row-reverse(反向水平排列)或 column-reverse(反向垂直排列)。
flex-wrap: 定义项目是否换行,可以是 nowrap(不换行)、wrap(换行)或 wrap-reverse(反向换行)。
flex-grow: 定义项目的伸缩比例,决定了在剩余空间中的分配比例。
flex-shrink: 定义项目的收缩比例,决定了当空间不足时如何收缩。
flex-basis: 定义项目的初始大小。
flex: 是 flex-growflex-shrinkflex-basis 的缩写。
align-items: 定义项目在交叉轴上的对齐方式。
align-content: 定义多行项目在交叉轴上的对齐方式。
justify-content: 定义项目在主轴上的对齐方式。

以下三、四俩部分内容html部分是一样的,如下

1
2
3
4
5
6
7
8
9
<body>
<div class="container">
<div class="item">item 1111</div>
<div class="item">item 2 </div>
<div class="item">item 3</div>
<div class="item">item4</div>
<div class="item">item 5</div>
</div>
</body>

三.调节flex子元素的大小flex-basis&flex-grow

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
* {
margin: 0;
padding: 0;
}

.container {
display: flex;
width: 500px;
border: 5px solid pink;
height: 50px;
}

.item {
/* 默认为1,如果为0就不缩小 */
flex-shrink: 2;
/* flex子元素的大小 */
flex-basis: 200px;
/* 1000px - 5 * (2x) = 500px */
/* x = 50px */
/* 200px - 2 * 50px = 100px */

background: skyblue;
}

.item:nth-child(1) {
/* 别人搜小2等份,我缩小1等份,所以我比别人大 */
flex-shrink: 1;
}

四.3-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
36
<style>
* {
margin: 0;
padding: 0;
}

.container {
display: flex;
width: 500px;
border: 5px solid pink;
height: 50px;
}

.item {
/* 默认为1,如果为0就不缩小 */
flex-shrink: 2;
/* flex子元素的大小 */
flex-basis: 200px;
/* 1000px - 5 * (2x) = 500px */
/* x = 50px */
/* 200px - 2 * 50px = 100px */

/* flex: grow shrink basis; */
/*默认值: flex: 0 1 auto; */

/* 让他们五等分 中间shrink不设置 */
flex: 1 0px;
background: skyblue;
}

.item:nth-child(1) {
/* 别人搜小2等份,我缩小1等份,所以我比别人大 */
/* flex-shrink: 1; */
}
</style>

flex容器基本概念