Search code examples
cssheightfluid-images

How to dynamically scale images per height using pure CSS?


This one goes out to the CSS pros:

I wonder if it's possible to achieve a image scaling behavior like on this site using pure CSS?

Be aware that the images only start scaling if the height of the browser window changes, not its width. (Just saying because all info on the web I found is about the alteration of the width.)

The real sticking point seems to be the different threshold values: Landscape-shaped images just start scaling down if they have the same height as the already downscaled portrait-shaped images.

Any feedback on that matter is highly appreciated!


Solution

  • You can do it with a combination of max-height, min-height, white-space and % height. The only negative is that each image has to have a class set to determine if it is vertical or horizontal.

    http://jsfiddle.net/Rgp6h/

    Example HTML:

    <div>
        <img src="http://placekitten.com/200/300" class="vert"/>
        <img src="http://placekitten.com/500/200" class="horiz"/>
        <img src="http://placekitten.com/200/300" class="vert"/>
        <img src="http://placekitten.com/400/300" class="horiz"/>
        <img src="http://placekitten.com/200/300" class="vert"/>
    </div>
    

    CSS:

    body,html{
        height: 100%;
    }
    
    div{
     white-space: nowrap;
        height: 100%;
    }
    
    img{
        min-height: 200px;
        height: 100%;
        vertical-align: top;
    }
    
    .horiz{
        max-height: 300px;
    }
    
    .vert{
        max-height: 500px;
    }