flex-grow 与 flex-shrink
文章目录
flex-grow
flex-grow用于处理flex容器剩余空间。
剩余空间分配计算
剩余空间 = flex容器宽度 - (项目1flex-basis + 项目2flex-basis + ... + 项目nflex-basis)
项目1分配空间 = [项目1flex-grow / (项目1flex-grow + 项目2flex-grow + ... + 项目nflex-grow)] * 剩余空间
示例
- 原始案例(剩余
300px)
<div class="row">
<div class="col"></div>
<div class="col"></div>
</div>
.row {
display: flex;
width: 600px;
height: 100px;
}
.row > .col:nth-child(1) {
background: red;
flex-basis: 100px;
flex-grow: 0;
}
.row > .col:nth-child(2) {
background-color: green;
flex-basis: 200px;
flex-grow: 0;
}
- 剩余空间分配
<div class="row">
<div class="col"></div>
<div class="col"></div>
</div>
.row {
display: flex;
width: 600px;
height: 100px;
}
.row > .col:nth-child(1) {
background: red;
flex-basis: 100px;
flex-grow: 2;
}
.row > .col:nth-child(2) {
background-color: green;
flex-basis: 200px;
flex-grow: 1;
}
-
项目1:
- 原宽度:100px
- 新宽度:300px
- 分配空间:200px
-
项目2:
- 原宽度:200px
- 新宽度:300px
- 压缩宽度:100px
flex-shrink
flex-shrink用于处理flex容器溢出空间。
溢出空间分配计算
溢出空间 = (项目1flex-basis + 项目2flex-basis + ... + 项目nflex-basis) - flex容器宽度
加权值 = (项目1flex-basis 项目1flex-shrink) + (项目2flex-basis 项目2flex-shrink) + (...) + (项目nflex-basis * 项目nflex-shrink)
项目1压缩宽度 = (项目1flex-basis 项目1flex-shrink / 加权值) 溢出空间
示例
- 原始项目(溢出
300px)
<div class="row">
<div class="col"></div>
<div class="col"></div>
</div>
.row {
display: flex;
width: 300px;
height: 100px;
}
.row > .col:nth-child(1) {
background: red;
flex-basis: 200px;
flex-shrink: 0;
}
.row > .col:nth-child(2) {
background-color: green;
flex-basis: 400px;
flex-shrink: 0;
}
- 溢出处理
<div class="row">
<div class="col"></div>
<div class="col"></div>
</div>
.row {
display: flex;
width: 300px;
height: 100px;
}
.row > .col:nth-child(1) {
background: red;
flex-basis: 200px;
flex-shrink: 1;
}
.row > .col:nth-child(2) {
background-color: green;
flex-basis: 400px;
flex-shrink: 2;
}
-
项目1:
- 原宽度:200px
- 新宽度:140px
- 压缩宽度:60px
-
项目2:
- 原宽度:400px
- 新宽度:160px
- 压缩宽度:240px
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论