Responsive Web Design: preserving images’ aspect ratio
Probably too obvious, but I thought I’d post it anyway.
One of the fundamental building blocks of responsive web design is ensuring images sit within their containers by a simple CSS rule img {max-width:100%;}
.
Generally, this works splendidly. But if you’re “reponsifying” an old site, you might find that the authors included the images’ heights and widths as attributes in the HTML.
In this case, the img {max-width:100%;}
can wreck the aspect ratio when the image is squeezed, as the width is forced by the CSS to shrink, but the height is still set in the HTML. See my photo of the most overloaded truck in the world and narrow the browser window.
This is easily cured without trawling through the markup and removing HTML height attributes. Simply extend your img CSS so it reads img {max-width:100%; height:auto;}
and aspect ratio is preserved.
12 Responses to “ Responsive Web Design: preserving images’ aspect ratio ”
The only problem is, that the css rule in the style sheet will be overridden by the in line rules every time
unless you add a !important before the end of that rule.
@Reuven You might think so, but see the demo – it works without no !important. If the width and height were specified with inline CSS (e.g. style=”width:640px;height:480px”) then that would trump the stylesheet on specificity, but evidently all CSS trumps width and height attributes, which makes perfect sense for exactly this kind of situation.
This technique (and some variations) also works with embedded YouTube videos. This is handy in a CMS world where end users paste code copied from YouTube into the page. It also trumps inline width/height attributes, but not inline styles.
To sort of address your last point, some blogging and CMS platforms embed inline styles on images. Blogger did it to me for a year or so and I had to constantly go in and remove them. Very frustrating since I still find posts where I missed them (was too lazy).
Further to the point about overriding the width and height attributes: CSS 2.1 section 6.4.4 specifies that presentational attributes in HTML “…are translated to the corresponding CSS rules with specificity equal to 0, and are treated as if they were inserted at the start of the author style sheet. They may therefore be overridden by subsequent style sheet rules.”
Hence why this works.
[…] via Bruce Lawson’s personal site : Responsive Web Design: preserving images’ aspect ratio. […]
I like the approach but it’s ugly to see when the image get squeezed.
unfortunately the image for your “Most Overloaded Truck in the World” is gone, and clicking on it says “404 error”. 🙁
Bruce,
Bleeding obvious. But one of those things that gets overlooked. Especially when you are deep in some “old IE” debugging hell. So totally worth blogging about. Infact its one of the 3 or 4 code snippets that it automatically in my CSS from the start of a project. Perhaps it’s worth putting on a post-it!