Interesting Approach to Responsive Images

A very interesting way to code your responsive images by Peter van Grieken, and it’s pretty straightforward actually! You’ll need 2 images (a smaller image for the smaller screen sizes, and of course a big image for the bigger screens), .. so far nothing really much new.

In this example the large image is being loaded when the viewport is at least 480px wide and the small image will be loaded for viewports smaller than 480px. The HTML for this image is, as you would expect for an image, pretty simple:

<img alt="" src="produce-a-smile.jpg" />

The best part of it all is that you have no extra attributes, no src-1, no srcset or even -elements. There’s not even extra HTTP-requests!

The proposal: <base> on steroids

<!-- Only applies to small screens (smaller than 480px) -->
<base data-href="/labs/resimg/images/small/" media="screen and (max-width: 480px)">

<!-- Only applies to large screens (large than 480px) -->
<base data-href="/labs/resimg/images/large/" media="screen and (min-width: 480px)">

<!-- Fallback, in this case the same as for small screens -->
<base href="/labs/resimg/images/small/">

Please notice the three <base> tags. The specification states that <base> is used only once in a document (only the first occurence and the rest is ignored), that’s why the data-href attribute is being used for the first two occurrences instead of href. This way the first two are invalid by default and only the third is used.

The second thing that Peter van Grieken added is the media attribute to the first two <base> tags. With a bit of Javascript (in the <head>) I check if the media attributes validate and if they do, add the href attribute and use the data-href as its value.

By setting the href attribute, the browser will use that <base> tag and ignore the third (fallback) one. You can read some of the pros and cons in the original article.


Article Navigation

Wait .. there's more!

Online CV Jan Rajtoral