英文:
Why does a flex-item with a display: flex collapses unless you give it an explicit width of 100%?
问题
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
.container {
  display: flex;
}
.component {
  display: flex;
  //width: 100%;
  height: 10px;
  background-color: red;
}
<!-- language: lang-html -->
<div class="container">
  <div class="component"></div>
</div>
<!-- end snippet -->
在没有width: 100%的情况下,.component会收缩并且不可见。加上width: 100%后,它会显示出来。
我的问题是为什么?
display: flex 默认情况下具有 width 为 100%,所以为什么我需要明确地设置 width 为 100%?
我知道.component 被转换成了一个 flex-item,它的默认 width 是 auto,这意味着 width 会根据内容收缩,由于.component没有内容,它会收缩到0,但它的 display 是 flex,flex 默认的 width 是 100%,所以我不应该需要明确设置 width 为 100%。
英文:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
    .container { 
      display: flex;
    }
    
    .component {
      display: flex;
      //width: 100%;
      height: 10px;
      background-color: red;
    }
<!-- language: lang-html -->
    <div class="container">
      <div class="component"></div>
    </div>
<!-- end snippet -->
without the width: 100%, the .component collapses, and is not shown. With width: 100%, it is shown.
My question is why?
display: flex has a width of 100% by default, so why do I need to explicitly set width to 100% again?
I know that the .component is turned into a flex-item which has a default width of auto, which means the width collapses to its content, and since the .component has no content, it collapses to 0, but it has a display of flex, which has a default width of 100%, so I should not have to set the width to 100% explicitly.
答案1
得分: 1
你的直觉是正确的,但在某些方面存在缺陷。弹性元素默认具有100%的宽度不是因为这是flex的作用,而是因为它被视为块级元素(而inline-flex被视为内联元素)。
弹性容器内的弹性元素不会在默认情况下自动增长的原因是,弹性容器的子元素实际上其flex属性设置为0 auto,除非另有规定(这是表示不增长、不缩小、基准是自动的缩写)。这就好像你手动将width设置为auto一样。
英文:
Your intuition is correct, but flawed on some aspects. The reason a flex element has width 100% "by default" isn't because that's flex's doing, but rather because it is treated as a block element (where inline-flex are treated as inline elements).
The reason a flex within a flex doesn't magically grow "by default" is because a flex's child element essentially has its flex property set to 0 auto unless specified (which is short for don't grow, don't shrink, basis is auto). Which sorts of acts as if you manually set width to auto.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论