Jenny Shoars
Jenny Shoars

Reputation: 1102

CSS - Maintain image ratio whose height is 100% when its width would force it to deform?

I've got an image whose height is set as 100%. This makes the image display correctly as I would expect so long as there's plenty of width. However, when the screen's width is reduced eventually the image loses it's ratio because the width is squished while the height still remains 100%. I would like to have the image always stretch to the maximum size possible within the container without losing it's ratio. In other words, it the width is the limiting factor, the image should use 100% width and maintain ratio, but if the height is the limiting factor, than the image should use 100% height while maintaining its ratio, and it should be able to switch between these. Is there a way to do this purely in CSS? Thanks!

Upvotes: 0

Views: 2442

Answers (1)

Stuart
Stuart

Reputation: 1168

This should keep the correct ratio (providing you don’t need the height to be set to 100% for some reason).

img{
    width: 100%;
    height: auto;
}

--EDIT--

If you want to retain a consistent height of the parent element then you can either:

  • Hide the overflowing image using overflow: hidden;. Although this means you will lose some of the image at larger sizes. See example.

  • Use max-width and max-height to stop the image growing at a certain point. This means you will potentially be left with some white space in the design. See example.

Upvotes: 1

Related Questions