Reputation: 43351
Is there any way using only CSS to set a div's height to be never greater than its width?
I have a series of images - portrait and landscape. I am currently containing them in a div set to 100% width with top-padding
of 66.6666666%
which constrains the image to fit within this 1:1.5 ratio.
This is fine for landscapes, but for portraits, this means they can never be taller than the the landscapes are at 100% width, so the total area of portrait images is significantly less than landscapes.
If I set the container ratio to 1:1 (with a top-padding
of 100%
), the portraits can achieve the same height as the landscapes are wide, however this means the landscapes have additional vertical space.
I'm looking for a way to constrain each image to a square area, without the extra space if it doesn't need it.
Upvotes: 1
Views: 1617
Reputation: 103790
You can achieve the desired behavior with vw units :
vw : 1/100th of the width of the viewport. (source : MDN)
vw units are supported by IE9+ (canIuse)
HTML :
<div>
<img src="http://lorempixel.com/output/people-q-g-1200-600-6.jpg" alt="" />
</div>
<div>
<img src="http://lorempixel.com/output/people-h-g-600-1200-9.jpg" alt="" />
</div>
CSS :
div{
width:100%;
max-height:100vw;
}
div > img{
max-width:100%;
max-height:100%;
width:auto;
height:auto;
display:block;
margin:0 auto;
}
Upvotes: 1
Reputation: 112
You should be able to set a height(or width) on the container of the image and by default the image should fit accordingly by using "background-size: contain" in your CSS.
Upvotes: 0