美文网首页
flex布局之flex-grow和flex-shrink的计算

flex布局之flex-grow和flex-shrink的计算

作者: spencer_sun | 来源:发表于2020-06-08 23:24 被阅读0次

1 flex 的基本属性介绍

        - flex 布局之父盒子的属性
            - align-items (交叉轴方向的对齐)
            - justify-content(主抽方向对齐)
            - flex-direction(主轴方向)
            - flex-wrap(是否多行显示)
            - flex-flow(flex direction和wrap 的简写)
            - align-content
         - 子项的属性
            - flex-grow(剩余空间的分配)
            - flex-shrink(超出盒子的缩小)
            - flex-basis(指定了 flex 元素在主轴方向上的初始大小)
            - flex(flex-basis,flex-grow,flex-shrink)
            - order(子项排布顺序, 越小越靠前)

2 flex-grow 的计算

结果展示

Screen Shot 2020-06-08 at 23.02.56.png

代码示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style type="text/css">
    .box {
      width: 400px;
      height: 500px;
      border: 1px solid #000000;
      display: flex;
    }
    .first {
      flex: 20px 1 0;
      height: 500px;
      background: #d3d4cc;
    }
    .second {
      flex: 30px 1 0;
      background: #e0e5df;
    }
    .third {
      flex: 50px 1 0;
      background: #b5c4b1;
    }
  </style>
  <body>
    <div class="box">
      <div class="item first">120</div>
      <div class="item second">130</div>
      <div class="item third">150</div>
    </div>
  </body>
</html>

计算过程
1 剩余可分配空间: 400-20-30-50 = 300
2 first 的分配:20+ 3001/3 = 120; second 的分配:30+ 3001/3 = 120; third 的分配50+ 300*1/3 = 120

flex-shrink的计算

flex-shrink和flex-growth的计算有不同,flex-shrink的比例是基于flex-basis的值的。

结果展示


Screen Shot 2020-06-08 at 23.19.59.png

代码示例

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <style type="text/css">
    .box {
      width: 400px;
      height: 500px;
      border: 1px solid #000000;
      display: flex;
    }
    .first {
      flex: 200px 1 1;
      height: 500px;
      background: #d3d4cc;
    }
    .second {
      flex: 300px 1 2;
      background: #e0e5df;
    }
    .third {
      flex: 500px 1 3;
      background: #b5c4b1;
    }
  </style>
  <body>
    <div class="box">
      <div class="item first">147.828</div>
      <div class="item second">143.484</div>
      <div class="item third">108.703</div>
    </div>
  </body>
</html>

计算过程
1 需要收缩的空间 500+200+300-400 = 600;
2 每个子项需要收缩的值 200Xn+300X2n+500X3n = 600; n = 6/23
3 first 的宽度 200 - 2006/23 = 147.828; second 的宽度 300 - 30026/23 = 147.828; third 的宽度 500 - 5003*6/23 = 147.828;

相关文章

网友评论

      本文标题:flex布局之flex-grow和flex-shrink的计算

      本文链接:https://www.haomeiwen.com/subject/pyvuzhtx.html