初见

文章 评论 浏览 31

初见 2022-05-04 13:54:06

flex: 0 1 auto的含义大家都说的很清楚,查了一些资料补充一下以下两种情况的子元素在分配主轴空间上的计算方式

主轴空间宽度有剩余,子元素最终的宽度?

<div class="parent">
    <div class="item-1"></div>
    <div class="item-2"></div>
    <div class="item-3"></div>
</div>

<style type="text/css">
    .parent {
        display: flex;
        width: 600px;
    }
    .parent > div {
        height: 100px;
    }
    .item-1 {
        width: 140px;
        flex: 2 1 0%;
        background: blue;
    }
    .item-2 {
        width: 100px;
        flex: 2 1 auto;
        background: darkblue;
    }
    .item-3 {
        flex: 1 1 200px;
        background: lightblue;
    }
</style>

主轴空间宽度不足,子元素最终的宽度?

<!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>
<body>
  <div class="container">
    <div class="left"></div>
    <div class="right"></div>
  </div>
  <style>
    * {
      padding: 0;
      margin: 0;
    }
    .container {
      width: 600px;
      height: 300px;
      display: flex;
    }
    .left {
      /* 285 */
      flex: 1 2 500px;  
      background: red;
    }
    .right {
      /* 314 */
      flex: 2 1 400px;
      background: blue;
    }
  </style>
</body>
  1. 总权重  500 * 2 + 400 * 1 = 1400 <br />
  2. 需要缩小的宽度 <br />
    left (500 * 2 / 1400) * 300 = 214.285714286<br />
    right (400 * 1 / 1400) * 300 = 85.714285714<br />
  3. 最后的宽度<br />
    left 500 - 214.285714286 = 285.714285714<br />
    right 400 - 85.714285714 = 314.285714286  <br />
</html>

第 154 题:弹性盒子中 flex: 0 1 auto 表示什么意思?

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文