【问题标题】:How to calculate the actual width of child elements of a flexbox container?如何计算 flexbox 容器子元素的实际宽度?
【发布时间】:2022-01-17 02:10:57
【问题描述】:

我有这样的 html 和 css 代码。我有两个问题:

  1. 当窗口宽度为 600px 时,理论上左框应该是 150px 宽度,因为它是 parent(600px)的 25%,但宽度是 120px。
  2. 右框无法达到100vw。它只需要widthOfParent - widthOfLeft。我想它应该以某种方式溢出并达到 100vw。
 <div class="container">
        <div class="left"></div>
        <div class="right"></div>
 </div>
* {
  margin: 0;
  padding: 0;
}
.container {
  height: 300px;
  /* your code here */
  display: flex;
  justify-content: start;
}

.left {
  background-color: #f44336;
  height: 100%;
  width: 25%;
  min-width: 100px;
}

.right {
  background-color: #2973af;
  height: 100%;
  width: 100vw;
}

codesanbox:https://codesandbox.io/s/admiring-darkness-cu99x?file=/src/styles.css:0-293

【问题讨论】:

    标签: html css user-interface flexbox frontend


    【解决方案1】:

    您正面临收缩效应。在所有情况下,100vw + 25% 的总宽度大于100%,因此这两个项目将同等缩小。

    由于您的容器也是全宽的,溢出将始终等于25%25vw。这两个元素都有默认的收缩值1,所以我们的总和等于125vw

    第一个元素的宽度将等于:25vw - (25vw * 25vw/125vw) = 20vw 第二项的宽度为:100vw - (25vw * 100vw/125vw) = 80vw

    逻辑上你可以看到总数为100vw20vw + 80vw),当屏幕宽度等于600px时,20vw等于120px

    为避免这种情况,请通过设置 flex-shrink:0 禁用第一项的收缩效果

    * {
      margin: 0;
      padding: 0;
    }
    
    .container {
      height: 300px; /* your code here */
      display: flex;
    }
    
    .left {
      background-color: #f44336;
      width: 25%;
      min-width: 100px;
      flex-shrink:0;
    }
    
    .right {
      background-color: #2973af;
      width: 100vw;
    }
    <div class="container">
      <div class="left"></div>
      <div class="right"></div>
    </div>

    相关:Why is a flex item limited to parent size?

    【讨论】:

      【解决方案2】:
      1. 使用“flex”属性而不是 flex 项的宽度
      .container {
          height: 300px;
          width: 600px; /* added fixed width for testing */
          display: flex;
          justify-content: start;
      }
      
      .left {
          background-color: #f44336;
          min-width: 100px;
          flex: 1; /* 1/4 ratio within the parent element, as the other flex item in the parent is "flex: 3;" */
      }
      
      .right {
          background-color: #2973af;
          flex: 3; /* 3/4 ratio within the parent element, as the other flex item in the parent is "flex: 1;" */
      }
      
      1. 右侧元素不能占据 100% 的宽度,因为它与 flex 父级内的左侧 div 一起,我们将宽度参数指定为“flex: value”。

      CSS flex 属性 https://www.w3schools.com/cssref/css3_pr_flex.asp

      【讨论】:

      • 嗨@Rpx,感谢您的回答。现在我知道我应该在 flexbox 中使用 flex 而不是 width。但是我还是不明白为什么右边的框不能达到我明确指定的宽度。
      猜你喜欢
      • 1970-01-01
      • 2017-07-03
      • 1970-01-01
      • 1970-01-01
      • 2016-08-16
      • 2020-12-11
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多