CSS Tip: Using max-width for flexible images

Posted in on 23 December 2010

When you are working with fluid or elastic website layouts or perhaps using CSS Media Queries, it’s essential that the designs cope with large images. For example, what happens when the layout is narrowed; does the image adjust in size or become cropped or, worse, does it ‘stick out’ of its containing element?

In these circumstances, one method is to scale the images down from their original size as the layout width changes. This is where the max-width property and, specifically, a value of 100% is useful:

.imgclass {
   max-width: 100%;
}

If you assign the max-width: 100% property/value to an image and remove the image width and height values from the (X)HTML, the result is that the image scales down nicely from its original size and its proportions are maintained. As the layout widens, the image scales up but it will not grow beyond its original size so the image does not become blurred at larger widths. You can see this effect on the middle screenshots, if you resize the browser window smaller, with this ecommerce templates page (there’s a minimum width on the layout so it won’t scale all the way down).

I think this is a really useful and quick solution for images in flexible website layouts.

PS: This solution scales the image down but if you want image scaling beyond the original image size, there are other options; see Richard Rutter’s article below.

More Info: Richard Rutter’s original experiments with max-width and image sizing · Ethan Marcotte explores Fluid Images

Related Posts

Comments

  1. flosen

    cool tip! thank you! cheers, florian

  2. diana.03

    Hi, I’m trying to build a site using a fluid grid. I assigned the images the max-width:100% but when I’m resizing the browser and the images is scaling down it gets blurry. What am I doing wrong? is there something I can do?

  3. Clive Walker (Author)

    @diana.03: I’ve not seen that problem myself but I know that some versions of Internet Explorer cannot scale images down as nicely. Not sure if this is the cause of your problem but see this article for an explanation and solution. Additionally, see also this fix.

  4. Steve Claflin

    It’s worth noting that you’re not limited to using 100% for the max-width. I like to use something slightly less, like 96%, to get separation between images in multiple floating containers. I could use margins or paddings instead, but often I don’t want those if the constraint isn’t applicable.

Comments

Enter your comment below. Fields marked * are required. You must preview your comment first before finally posting.