How can I have flexible css image sizing with max height and width while preserving image aspect ratio, without javascript?

StackOverflow https://stackoverflow.com/questions/8967212

Question

I really thought this would be elsewhere on stack overflow, but I searched fruitlessly for length of time. Forgive me if I missed it.

I have a set of images who need to be made as large as possible (width: 100% to container elem) as long as the container does not grow too wide or the image too tall because of the container width. Aspect ratio needs to be preserved.

I thought I could do this with

img { width: 100%; height: auto; max-width: 500px; max-height: 250px; }

The idea was that if the image hit either the max-width or the max-height given the width and the aspect ratio, it would no longer grow. In reality, this causes the image width to size as wide as possible, but breaks the aspect ratio (squishing the image to max-height) when it is too tall, instead of preventing the image from growing wider.

Is there a better way to go about this? I would like to avoid javascript if possible. My tests are in Firefox 9.

Was it helpful?

Solution

You can use media queries to create a stairstep of fixed image sizes, and then go like this:

@media screen and (min-width: 701px) and (max-width: 900px) {
    img {
        width:  800px;
        height: auto;
    }
}

@media screen and (min-width: 901px) and (max-width: 1100px) {
    img {
        width:  1000px;
        height: auto;
    }
}

Not very pretty, but it works.

OTHER TIPS

A bit old but using top or bottom padding will keep your aspect ratio. Divide height/width and apply that percentage to the padding top or bottom. It can get tricky sometimes but it works.

Here is a good article about it: http://voormedia.com/blog/2012/11/responsive-background-images-with-fixed-or-fluid-aspect-ratios

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top