-
Book Overview & Buying
-
Table Of Contents
-
Feedback & Rating

Responsive Media in HTML5
By :

The title of this exercise is a real mouthful, but serves to highlight an interesting experiment: "What if we could use data tags to switch images?"
The immediate benefit of source shuffling is that it keeps CSS media queries out of the HTML markup (to see what I mean, take a look at the HTML code used in Working with the <picture> tags in the next section.)
It's an interesting concept and one you may want to consider using; to see how it works, we'll use an adapted version of an example created by the UX designer Jordan Moore. This uses JavaScript-based Conditional CSS library by Jeremy Keith to great effect. To see what I mean, let's get going on a demo to see how it works:
datatags.html
in the root of our project area:<!DOCTYPE html> <html> <head> <title>Responsive Images using data- tags - Demo</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width,initial-scale=1"> <link rel="stylesheet" href="css/datatags.css"> <script src="js/jquery.min.js"></script> <script src="js/onmediaquery.min.js"></script> <script src="js/datatags.js"></script> </head> <body> <img class="thumbnail" src="img/small.jpg" data-medium="img/ medium.jpg" data-large="img/large.jpg" alt="Responsive images example"> </body> </html>
small.jpg
, medium.jpg
, and large.jpg
and save these to the img
subfolder in our project folder.jquery.min.js
, onmediaquery.min.js
, and datatags.js
should be extracted from the code download and saved into the js
subfolder of our project area.datatags.css
in our css
subfolder:img { max-width: 100%; } body:after { content: "global"; display: none; } @media screen and (min-width: 35em) { body:after { content: "tablet"; display: none; } } @media screen and (min-width: 56em) { body:after { content: "desktop"; display: none; } }
The key to note in this demo is that we will only see the small.jpg
image on mobile devices where the viewport is already smaller. On larger devices and desktops, either the medium.jpg
or large.jpg
images will be shown instead as dictated by the media query in effect.
Change the font size
Change margin width
Change background colour