GuitarExtended
GuitarExtended

Reputation: 827

Auto-resize image in flex item

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.

Upvotes: 10

Views: 16331

Answers (2)

huan feng
huan feng

Reputation: 8623

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>

Upvotes: 3

Mattonit
Mattonit

Reputation: 601

You can use this class:

.img-fluid {
    max-height:100%;
    height:auto;
}

Don't forget to add .img-fluid to your img

Upvotes: 0

Related Questions