flex属性介绍

用于控制flex布局下,子元素的伸缩行为。实际上是三个子属性的简写。

1
flex:<flex-grow> <flex-shrink> <flex-basis>;
  • flex-grow: 定义项目的扩展比例。默认值为0。

  • flex-shrink: 定义项目的收缩比例。默认值为1。

    如果容器空间不足,子项目会根据flex-shrink的值收缩,值越大,收缩越多。比如flex-shrink:3收缩比flex-shrink:1收缩得多。

  • flex-basis: 定义项目的初始大小。默认值为auto。

  • 内容类似于width,但是比width的优先级高。可以设置为固定值(200p x 、30%、content)。

常见的简写形式

  • flex:initial(默认值)

    1
    flex: 0 1 auto; /*不扩展,不收缩、初始大小为内容宽度*/

    项目内保持内容宽度,空间不够了就会收缩。

  • flex:auto

1
flex: 1 1 auto/*可扩展,可收缩,初始大小为内容宽度*/

项目根据内容自动调整,并参与剩余空间的分配。

  • flex:none
1
flex: 0 0 auto; /*不扩展、不收缩、固定为内容宽度*/

项目完全固定宽度,不响应容器的变化。

  • flex: ,例如常用的flex:1。
1
flex: 1 1 0%; /*可扩展、可收缩,初始大小为0%(强制平分剩余空间)*/

举例说明

  • 常用的实现三等分
1
2
3
4
5
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child"></div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
.parent {
display: flex;
width: 320px;
gap: 10px;
border: 1px solid green;
}
.child {
height: 50px;
}
.child:nth-child(1) {
background-color: red;
flex: 1;
}
.child:nth-child(2) {
background-color: yellow;
flex: 1;
}
.child:nth-child(3) {
background-color: blue;
flex: 1;
}

image-20250210214330342

如果只有红色的flex:1,则css有:

1
2
3
4
5
6
7
8
9
10
.child:nth-child(1) {
background-color: red;
flex: 1;
}
.child:nth-child(2) {
background-color: yellow;
}
.child:nth-child(3) {
background-color: blue;
}

image-20250210214642045

则单个flex:1占满了总长度-gap累计长度

如果子项存在内容了,默认内容宽度

1
2
3
4
5
6
7
<div class="parent">
<div class="child"></div>
<div class="child"></div>
<div class="child">
<div style="padding: 10px">我是内容</div>
</div>
</div>

image-20250210221736683

  • 固定混合动态

比如常见的侧边栏固定宽度,主内容区填充剩余空间。

1
2
3
4
<div class="container">
<div class="sidebar"></div>
<div class="main"></div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.container {
display: flex;
gap: 10px;
width: 800px;
border: 1px solid red;
}
.sidebar {
flex: 0 0 200px;
height: 100px;
background-color: yellow;
}
.main {
flex: 1;
height: 100px;
background-color: green;
}

image-20250210223706452

  • 响应式收缩
1
2
3
<div class="container">
<div class="item"></div>
</div>
1
2
3
4
5
6
7
8
9
10
11
12
.container {
display: flex;
width: 300px;
border: 1px solid red;
height: 100px;
gap: 10px;
}
.item {
flex: 1 1 400px;
background-color: yellow;
margin-left: 30px;
}

image-20250210224112850