Search code examples
cssimage-scaling

CSS: Displaying/scaling images without messing up the proportions?


I have an image, its 120 x 90 px for example. Now I want to display a smaller version of that image, with 80 x 50 px for example. I know I can use width and height which will work for images having the same size.

Now my problem is that I have different images, which have a different original size and just using a static width and height will make some images look strange (because the proportions are messed up).

How could I handle such cases? Is it possible in pure CSS, or do I need some JS?

Thanks!


Solution

  • We call this dynamic divs the image will resize when de div is smaller or bigger.

    An example

    img {
        max-width: 100%;
        height: auto;
        width: auto\9; /* ie8 */
    }
    
    .video embed,
    .video object,
    .video iframe {
        width: 100%;
        height: auto;
    }
    
    <div style="max-width:500px;">
        <img src="..." />
    </div>
    

    FIDDLE note: if you resize your browser window you see that the image is resized too.

    If you make a small div the image is small too. etc.