The CSS max-width property has long been a favorite of mine, most often used to restrict the flow of content depending on the user’s browser, such as we see in elastic layouts. Since I began making WordPress themes a couple years ago I’ve used max-width as a staple rule for media in my stylesheet, starting with images that might appear in a post (e.g. .post):
.post img { max-width: 100%; }
This prevents the sort of thing we often see when an image is slapped into a blog post without being resized especially for that design. Here’s an example this just popped up in my Google Reader:
In addition to preventing IMGs from breaking out of the box (or, worse, growing the box) this can be applied to other elements as well. In the case of my themes’ CSS I also include OBJECT (and, just to be safe, EMBED):
.post img, .post object, .post embed { max-width: 100%; }
With the entrance of HTML 5 one can imagine adding/replacing AUDIO and VIDEO in this list of selectors.
I’m thinking about this today because on Twitter Jeffrey Zeldman RT’ed Stephanie Hobson quoting Ethan Marcotte:
This is a fine solution, and reminded me that just last week I was talking with colleague Ken Woodward applying max-width in a more generic fashion–more generic, even, than to all IMGs:
div * { max-width: 100%; }
This is very broad, of course, and could cause problems in a number of particular designs, however I’m thinking the principle is still valid, particularly as it applies to inline elements, for the W3 reminds us:
If an inline box cannot be split (e.g., if the inline box contains a single character, or language specific word breaking rules disallow a break within the inline box, or if the inline box is affected by a white-space value of nowrap or pre), then the inline box overflows the line box.
Why wouldn’t I just write the rule without the DIV ancestor? Most elements that I need to control naturally fall within a DIV, and this limitation helps me feel safer, though I haven’t done enough testing to see how when/where it might fail. I am certain there is probably not enough specificity to override width problems that may be caused by miscalculated pixel widths of directly targeted descendant elements (i.e. DIVs), but those should probably have been done in percentages anyway. If specificity is a problem, adding a relevant parent CLASS or ID to the selector could probably solve it.

