CSS Tip: Using max-width for flexible images
I wrote this post a while back. The content can still be relevant but the information I've linked to may not be available.
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.
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
Comments
19 Oct 2011 16:50:58
cool tip! thank you! cheers, florian
08 Dec 2011 21:37:06
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?
09 Dec 2011 09:46:54
@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.
22 May 2013 13:44:20
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 are OFF for this post.