Search code examples
cssimageimage-scalingaspect-ratio

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


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.


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.