Look at my responsive image!

Produce a smile

In this example I have two images, a small one (/images/small/produce-a-smile.jpg) and a large one (/images/large/produce-a-smile.jpg), the large one is loaded when the viewport is at least 480px wide and the small one for viewports smaller than 480px.

The HTML for this image is, as you would expect for an image, pretty straightforward:

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

That's it! No extra attributes, no src-1, no srcset or even <picture>-elements. There's not even extra HTTP-requests.

Current situation

All current proposals to solve the responsive images problem focus on extending the <img> tag. Adding attributes with complex or very verbose syntax or wrapping it in new elements while trying not to break current functionality.

Although I find <picture> the most elegant of the current proposals, it seems unlikely we'll get it. It even seems unlikely we'll have any solution any time soon while politics and personal preference get in the way. (Update: Apparently <picture> is back in the game)

My proposal: <base> on steroids

Let me start with the code I use on this page:

<!-- 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/">

Let me go through this small piece of code. The first thing you'll notice, is that there are three <base> tags. The specfication states that <base> is used only once in a document (only the first occurence and the rest is ignored), that's why I use the data-href attribute for the first two occurences instead of href. This way the first two are invalid by default and ony the third is used.

The second thing I did is add 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.