Search code examples
cssimageflexbox

flexbox column Resize image according to text length


Given a flexible box column, how can I resize image as text length increases to fit.

.container {
  width: 400px;
  height: 300px;
  border: 3px solid green;
  padding: 4px;
  display: flex;
  flex-direction: column;
}

.img-wrapper {
  /* display: flex; */
}

.img-wrapper img {
  max-width: 100%;
  /* min-height: 0px; */
  object-fit: cover;
}
<div class="container">
  <div class="img-wrapper">
    <img src="https://static.billboard.com/files/media/talib-kweli-2018-cr-Dorothy-Hong-billboard-1548-compressed.jpg" />
  </div>
  <div class='text'>
    this is a cool paragraph about the angry theicn shfieh that eats and is not pfeifol about the nutehc chartogret including but not adfentily of the crooked and devque thandilbot. Piej kargrid angy that iejf othersome to the compact shiferboth
  </div>
</div>

If the image is top-level, this simple CSS solves:

img {
  min-height: 0px;
  object-fit: cover;
}

Solution

  • .container {
        width: 400px;
        height: 300px;
        border: 3px solid green;
        padding: 4px;
        display: flex;
        flex-direction: column;
    }
    
    .img-wrapper {
        /* display: flex; */
        min-height: 0;  /* make it so it won't be stretch by children */
    }
    
    .img-wrapper img {
        max-width: 100%;
        max-height: 100%;  /* make the image auto scale to fit both width and height */
        object-fit: cover;
    }
    <div class="container">
      <div class="img-wrapper">
    <img src="https://static.billboard.com/files/media/talib-kweli-2018-cr-Dorothy-Hong-billboard-1548-compressed.jpg" />
      </div>
      <div class='text'>
    this is a cool paragraph about the angry theicn shfieh that eats and is not pfeifol about the nutehc chartogret including but not adfentily of the crooked and devque thandilbot. Piej kargrid angy that iejf othersome to the compact shiferboth
      </div>
    </div>