Huzaifa Zahid
Huzaifa Zahid

Reputation: 37

Make image container adjust its height based on sibling container content?

I want the .content-container to take up as much height as needed based on its content, and I want the .image-container to adjust its height dynamically to match the .content-container.

The problem I'm facing is that when I add an image to the .image-container, it increases the height of the .main-container, and the .content-container ends up stretching to match the image's height instead. I need the opposite behavior: the image's height should adjust to match the height of the .content-container.

How can I make the image container's height DYNAMICALLY match the height of the content container? Any help would be appreciated!

<div class="main-container">
  <div class="image-container">
    <img src="https://images.unsplash.com/photo-1464146072230-91cabc968266?q=80&w=1740&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D" alt="">
  </div>
  <div class="content-container">
    <h1>test1</h1>
    <h1>test1</h1>
    <h1>test1</h1>
    <h1>test1</h1>
    <h1>test1</h1>
    <h1>test1</h1>
    <h1>test1</h1>
    <h1>test1</h1>
    <h1>test1</h1>
  </div>
</div>


.main-container {
  width: 100%;
  background-color: red;
  display: flex;
  flex-wrap: wrap;
}

.image-container {
  flex: 0 0 50%;
  background-color: aqua;
}

.image-container img {
  height: 100%;
  width: 100%;
}

.content-container {
  flex: 0 0 50%;
  background-color: orange;
}


Upvotes: 0

Views: 43

Answers (1)

You can do this by changing the .image-container position to relative and the img position to absolute.

.image-container {
    flex: 0 0 50%;
    background-color: aqua;
    position: relative;
  }
  
  .image-container img {
    height: 100%;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
  }

Upvotes: -1

Related Questions