flex:1是什么?

68 阅读2分钟

flex:1 是 flex-grow: 1, flex-shrink: 1,flex-basis: 0% 的缩写;

flex-basis

flex初始大小

flex-grow

flex-grow是将剩余的空间,根据flex-grow的值平分,然后加到flex-basis上

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>flex-grow</title>
     <style>
      #content {
        display: flex;
        width: 500px;
      }
      #content div {
        flex-basis: 60px;
      }
      .box {
        flex-grow: 1;
      }
      .box1 {
        flex-grow: 4;
      }
    </style>
  </head>
  <body>
    <p>内容的宽度是500px,flex item的flex-basic是60px。</p>
    <p>A、B 为 flex-grow:1。C和D为 flex-grow:4</p>
    <div id="content">
      <div class="box" style="background-color: red">A</div>
      <div class="box" style="background-color: lightblue">B</div>
      <div class="box1" style="background-color: yellow">C</div>
      <div class="box1" style="background-color: brown">D</div>
    </div>
  </body>
</html>


可以看到子元素的flex-basis加起来是240px,父容器分完以后剩下260px,ABCD的flex-grow加起来10,那么每一份是26px,最终AB是60px + 26px = 86px,CD是60px + 26px * 4 = 164px。

flex-shrink

<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>flex-shrink</title>
    <style>
      #content {
        display: flex;
        width: 500px;
      }
      .box {
        flex-shrink: 1;
      }
      .box1 {
        flex-shrink: 4;
      }
    </style>
  </head>
  <body>
    <p>内容的宽度是500px,flex item的flex-basic总和是1000px。</p>
    <div id="content">
      <div class="box" style="background-color: red; flex-basis: 100px">A</div>
      <div class="box" style="background-color: lightblue; flex-basis: 200px">B</div>
      <div class="box1" style="background-color: yellow; flex-basis: 300px">C</div>
      <div class="box1" style="background-color: brown; flex-basis: 400px">D</div>
    </div>
  </body>
</html>

要扣除的容量计算是没有问题的,还是子元素的flex-basis加起来减去父元素的宽度。

平分的比例是子项目的flex-basis * flex-shrink 除以每个子项目的flex-basis * flex-shrink之和。

上面例子

A的flex-basis 是100px, flex-shrink 是 1

B的flex-basis 是200px, flex-shrink 是 1

C的flex-basis 是300px, flex-shrink 是 4

D的flex-basis 是400px, flex-shrink 是 4

要平分的容量 NT = 100 + 200 + 300 + 400 - 500 = 500

最终A的宽度 = 100 - 100 * 1 / (100 * 1 + 200 * 1 + 300 * 4 + 400 * 4) * NT = 83.87096774193549

B的宽度 = 200 - 200 * 1 / (100 * 1 + 200 * 1 + 300 * 4 + 400 * 4) * NT = 167.74193548387098

C的宽度 = 300 - 300 * 4 / (100 * 1 + 200 * 1 + 300 * 4 + 400 * 4) * NT = 106.45161290322582

D的宽度 = 400 - 400 * 4 / (100 * 1 + 200 * 1 + 300 * 4 + 400 * 4) * NT = 141.93548387096774