Reputation: 180
If I create a 2x2 grid of divs using flex box wrap, then place an image in each div:-
<div id="wrapper">
<div class="item"><img src="http://via.placeholder.com/100x500"></div>
<div class="item"><img src="http://via.placeholder.com/100x500"></div>
<div class="item"><img src="http://via.placeholder.com/100x500"></div>
<div class="item"><img src="http://via.placeholder.com/100x500"></div>
</div>
#wrapper {
display: flex;
flex-wrap: wrap;
height: 100vh;
background-color: burlywood;
}
.item {
flex-grow: 1;
width: 50%;
background-colour: bisque;
}
If the image's native height is deeper than the flex item it will push my content deeper than the 100vh I set my wrapper to.
I want each image to fill the height of its flex item div, in this example 50% of the screen height, and for the image width to be in the correct ratio.
I've tried setting the image height to 100% of its container but I can't get it to work. (unless the image native height is shorter, then it will expand to fit).
It also works if I explicitly set the height of the flex item divs to 33.333% but that doesn't seem like the right solution to me.
Upvotes: 1
Views: 1585
Reputation: 2643
You need to set your image's height only to make it keep the correct ratio. Add the following class to your CSS to apply height of 50vh
and I think your problem will be resolved if I understood it correctly.
.item img {
height:50vh;
}
You can play around with the adjustments to get what you need after that.
Hope this helps.
Upvotes: 0
Reputation: 7614
Another solution is to set the .item
height to 50%, and the give .item img
a maximum height, like this:
#wrapper {
display: flex;
flex-wrap: wrap;
height: 100vh;
background-color: burlywood;
}
.item {
flex-grow: 1;
width: 50%;
background-color: bisque;
height: 50%;
}
.item > img {
max-height: 100%;
}
<div id="wrapper">
<div class="item"><img src="http://via.placeholder.com/100x500"></div>
<div class="item"><img src="http://via.placeholder.com/100x500"></div>
<div class="item"><img src="http://via.placeholder.com/100x500"></div>
<div class="item"><img src="http://via.placeholder.com/100x500"></div>
</div>
Here's a fiddle if that's your preference.
Upvotes: 1