zhangdizhangdi

Flex

基础

  • flex-row 扩张,宽度总和 < 容器宽度
  • flex-shrink 收缩,宽度总和 > 容器宽度
  • flex-basis
    • ​auto​ 使用子元素的尺寸
    • 0 子元素宽度为0
flex-grow flex-shrink flex-basis
默认 0 1 auto
none 0 0 auto
auto 1 1 auto
n(非负) n 1 0%
长度或百分比 1 1 长度或百分比
n,m(非负) n m 0
n,长度或百分比 n 1 长度或百分比
  • flex:1 不管内容多少,一般都是平分空间,空间大小都一致
  • flex:auto根据内容的大小来分,不是平的(除非内容都是一样,才平分)

计算

  1. 各个子元素根据 flex-basis 的值,填充父元素
  2. 根据填充后的剩余空间大小根据flex-grow和flex-shrink伸缩

flex-grow

html
<div class="parent-grow">
  <div class="item-1">64</div>
  <div class="item-2">104</div>
  <div class="item-3">132</div>
</div>
<style>
  .parent-grow {
    display: flex;
    width: 300px;
    div {
      height: 100px;
      line-height: 100px;
      text-align: center;
      color: #000;
    }
    .item-1 {
      width: 40px;
      flex: 2 1 0%;
      background: pink;
    }
    .item-2 {
      width: 40px;
      flex: 2 1 auto;
      background: yellow;
    }
    .item-3 {
      flex: 1 1 100px;
      background: wheat;
    }
  }
</style>
执行结果
64
104
132
  1. 剩余空间 = 300 - 0 - 40 - 100 = 160
  2. 等分:2+2+1=5
    • item-1 = 0 + 2/5 * 160 = 64
    • item-2 = 40 + 2/5 * 160 = 104
    • item-3 = 100 + 1/5 * 160 = 132

flex-shrink

html
<div class="parent-shrink">
  <div class="item-1"></div>
  <div class="item-2">107.14</div>
  <div class="item-3">192.86</div>
</div>

<style>
  .parent-shrink {
    display: flex;
    width: 300px;
    div {
      height: 100px;
      line-height: 100px;
      text-align: center;
      color: #000;
    }
    .item-1 {
      width: 100px;
      flex: 2 1 0%;
      background: red;
    }
    .item-2 {
      width: 200px;
      flex: 2 1 auto;
      background: yellow;
    }
    .item-3 {
      flex: 1 1 360px;
      background: wheat;
    }
  }
</style>
执行结果
107.14
192.86
  1. 溢出空间 = 0 + 200 + 360 - 300 = 260
  2. 权重:1*0 + 1*200 + 1*360 = 560
    • item-1 = 0
    • item-2 = 200 - (1*200)/560 * 260 = 107.14
    • item-3 = 360 - (1*360)/560 * 260 = 192.86

参考