skip to Main Content

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>

2

Answers


  1. <style>
    #parent {
      display: flex;
      flex-direction: column;
      min-width: fit-content;
      max-width: 240px;
    }
    
    #child1 {
      word-wrap: break-word; 
    }
    
    #child2 {
      flex-grow: 1; 
    }
    
    #child2 img {
      width: 100%; 
      height: auto; 
    }
    </style>
    
    <div id="parent">
      <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>

    If you want the text to wrap onto the next line after reaching the maximum width of the parent
    ==== update ====

    #parent {
      display: flex;
      flex-direction: column;
      min-width: fit-content;
      max-width: 240px;
    }
    
    #child1 {
      word-wrap: break-word; 
    }
    
    #child2 {
      flex-grow: 1; 
    }
    
    #child2 img {
      width: 100%; 
      height: auto; 
    }
    

    Here is HTML update:

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

    I hope this will help you.

    === Update with grid ====

    <style>
    #parent {
      display: grid;
      grid-template-columns: min-content 1fr;
      min-width: fit-content;
      max-width: 240px;
    }
    
    #child1 {
      word-wrap: break-word; 
    }
    
    #child2 {
      width: 100%; 
    }
    
    #child2 img {
      width: 100%; 
      height: auto; 
    }
    </style>
    
    </head>
    <body>
    
    <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>
    Login or Signup to reply.
  2. Quickly, To illustrate my comment How to prevent image enlarging the cell in flexbox CSS , but there got to be duplicates about this

    #parent {
      display: flex;
      flex-direction: column;
      min-width: 10px;
      max-width: 240px;
      border:solid;
    }
    
    #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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search