responsive design

Pure CSS Responsive Images (Yes, without JavaScript)

There are numerous ways to implement responsive images in webpages. However, all solutions I came across make use of JavaScript. That made me wonder whether it would be possible to implement responsive images without the use of JavaScript.

I came up with this solution that is pure CSS.

How does it work?

I placed an <img> tag within a <span>. The src attribute will fetch the mobile version of the image from the server. Then I also include a bit of CSS within the <span> element.

What?! Embedded CSS in the HTML document?

Yes, that is perfectly valid in HTML5 as long as you add the scoped attribute. In the CSS I use an @media query to add the high resolution image as a background to the <span> from a certain breakpoint. In the code below I’ve only added one breakpoint, but you can add as many as you like of course.

By using a background image, it will only be fetched from the server when needed. That is, only when the media query is satisfied. The <img> will make sure the <span> will have the proper width and height ratio so the background image on that <span> is displayed properly.

Show me the code

Here is the code to make it all work.

The HTML

First the HTML.


<span class="magik-responsive-image" id="image-01">
<img src="http://dummyimage.com/200x150/cdcdcd/000/?text=lo-res">
<style scoped>
@media screen and (min-width: 701px){#image-01{background-image:url(http://dummyimage.com/1600x1200/dcdcdc/000/?text=hi-res);}}
</style>
</span>

The CSS

We also need a little bit of extra CSS to hide the lo-res image when the hi-res image should be displayed. The trick is to add background-size: 100%;, this will stretch the background while maintaining the aspect ratio.


.magik-responsive-image {
background-repeat: no-repeat;
background-size: 100%;
display: block;
position: relative;
}

.magik-responsive-image img {
max-width: 100%;
width: 100%;
}

@media screen and (min-width: 701px) {

.magik-responsive-image img{
opacity: 0;
}
}

The pros

  • No JavaScript
  • Simple to implement
  • Also works for videos (I’ll post about that in a future post)

The cons

  • On desktop there are two requests made to the server.
  • The scoped attribute of the <style> tag is not yet supported in any of the major browsers. Because of this, we need to add an id, but this usually is not a problem to add in the back-end code.

 

 The Demo

have a look at this fiddle