Search code examples
htmlcssflexboxgrid

How to prevent image enlarging the cell in flexbox CSS


Flexbox parent width should be decided by text inside child1. image inside child2 should grow when parent grows. And parent div should grow until max-width But when I put my image inside it enlarges my parent.

#parent {
  display: flex;
  flex-direction: column;
  min-width: 10px;
  max-width: 240px;
}
<div id="parent">
  <div id="child1">text here should decide parent width</div>
  <div id="child2"><img src="https://picsum.photos/400/100" alt="Image" /></div>
</div>


Solution

  • Quickly, To illustrate my comment How to prevent image enlarging the cell in flexbox CSS , but there got to be duplicates about this

    .parent,
    #parent {
      display: flex;
      flex-direction: column;
      min-width: 10px;
      width:max-content;
      max-width: 240px;
      border: solid;
    }
    
    .parent img,
    #parent img {
      width: 0;
      min-width: 100%;
    }
    <div id="parent">
      <div id="child1">text here should decide parent width</div>
      <div id="child2"><img src="https://picsum.photos/400/100" alt="Image" /></div>
    </div>
    
    <div class="parent">
      <div>t</div>
      <div><img src="https://picsum.photos/400/100" alt="Image" /></div>
    </div>
    
    <div class="parent">
      <div>text</div>
      <div><img src="https://picsum.photos/400/100" alt="Image" /></div>
    </div>
    
    <div class="parent">
      <div>text here</div>
      <div><img src="https://picsum.photos/400/100" alt="Image" /></div>
    </div>
    <div class="parent">
      <div>text here should </div>
      <div><img src="https://picsum.photos/400/100" alt="Image" /></div>
    </div>
    <div class="parent">
      <div>text here should decide parent width . IS that clear?</div>
      <div><img src="https://picsum.photos/400/100" alt="Image" /></div>
    </div>