Search code examples
cssflexboxaspect-ratio

Empty div with aspect ratio does not appear if parent is a flex element


Please check out the snippet below: why do I see the first empty div with the correct aspect ratio, but not the same box wrapped in a flex element? And what can I do to see in the second case as well?

.box {
  aspect-ratio: 16/9; 
  background: yellow;
  border: 5px solid red; 
  margin-bottom: 20px;
}

.flex {
  display: flex;
}
<div class="box"></div>
<div class="flex">
  <div class="box"></div>
</div>


Solution

  • The initial setting of a flex item is flex-grow: 0.

    That's what you're seeing for the box element in the flex container.

    no growth + no content = no width
    

    Just add flex-grow: 1 or flex: 1 to give the item full width.

    .box {
      aspect-ratio: 16/9; 
      background: yellow;
      border: 5px solid red; 
      margin-bottom: 20px;
      flex-grow: 1; /* NEW */
    }
    
    .flex {
      display: flex;
    }
    <div class="box"></div>
    <div class="flex">
      <div class="box"></div>
    </div>

    https://developer.mozilla.org/en-US/docs/Web/CSS/flex-grow