Why does a flex-item with a display: flex collapses unless you give it an explicit width of 100%?

huangapple go评论44阅读模式
英文:

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 默认情况下具有 width100%,所以为什么我需要明确地设置 width100%

我知道.component 被转换成了一个 flex-item,它的默认 widthauto,这意味着 width 会根据内容收缩,由于.component没有内容,它会收缩到0,但它的 displayflexflex 默认的 width100%,所以我不应该需要明确设置 width100%

英文:

<!-- 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 -->

    &lt;div class=&quot;container&quot;&gt;
      &lt;div class=&quot;component&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;

<!-- 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.

huangapple
  • 本文由 发表于 2023年6月22日 14:40:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76529178.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定