Auto-resize image in flex item

css, flexbox

Solution

Is this layout you wanted?

Using `flex: 1 1 0` to control the sub-container and using `width: 100%` could make the image to fit the container.

.main-container{
  border: 3px solid green;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
}
.sub-container{
    flex-grow: 1 1 0;
    background-color: green;
    display: flex;
}

.sub-container img {
   width: 100%;
   height: 100%;
}
<div class="main-container">
    <h1>A title</h1>
    <p>Some text</p>
    <div class="sub-container">
        <img src="https://picsum.photos/1080/600">
    </div>
</div>

Problem

I have the following html : ``` <div class="main-container"> <h1>A title</h1> <p>Some text</p> <div class="sub-container"> <img src=""> </div> </div> ``` With the following CSS : ``` .main-container{ width: 100%; height: 100%; display: flex; flex-direction: column; } .sub-container{ flex-grow:2; background-color: green; } ``` Please note that I don't know the size of the container above "main-container". I'm using flex because I want the div in "main-container" to occupy all the remaining space at the bottom. What I want is to have an image in "sub-container" which fits its parent's size in both directions (height and width). Right now if I add an image into "sub-container" it overflows and doesn't get scaled at all. I know that flex only works for immediate children (i.e. "sub-container" but not the image inside). I tried to use flex on "sub-container" too, but I couldn't achieve anything satisfactory.

Original source

Related problems