How To Use HTML5 <picture> Element To Achieve Responsive Image
Responsive Design may be here to stay but there are many issues that need to be addressed when it comes to making images responsive. Although responsive images automatically resize itself upon the viewport size (which is technically easy), one problem users face is that the image vocal point will become barely visible when the image becomes too small.
The ideal consensus among web developers is that the actual dimension should be responsive too. The browser should be able to load smaller or larger images in accordance to the viewport size. That way we can direct and deliver the best image proportion rather than the shrunken image (as shown).
This is where the HTML5
picture element comes in. The
picture allows us to provide multiple image sources and control the delivery through Media Queries. Though there isn’t any browser that implement this element yet, we can use a polyfill called Picturefill to do this. Let’s see how it’s done, shall we?
Recommended Reading: 5 Methods To Serve True Responsive Images
picture element now. To get started, download the script in the Github repository and put the
I have prepared an image in three different dimensions, as follows. The image has been cropped to preserve focus on the person in the image. The plan here is that we will show the smallest size in small screens and the larger image in large screens.
Using Picture Element
Picturefill can work in two ways: we can embed
srcset in the
img tag or use the
picture element. Here we will opt for the
picture element as it is more manageable, easier to undestand, and more readable.
picture wraps mulitple
source elements pointing to the image source, as follows.
<picture> <source srcset="img/person-xsmall.jpg" media="(max-width: 480px)"> <source srcset="img/person-small.jpg" media="(max-width: 640px)"> <source srcset="img/person-med.jpg"> <img srcset="img/person-med.jpg" alt=""> </picture>
source element, as you can see from the above code snippet, is set with
media attribute. In this attribute we specify the viewport breakpoint on which the image should be presented. You can see the effect immediately.
Check out our demo page, and resize the viewport size, you should find the image shown within the specified viewport width.
Picturefill for WordPress
If you are using WordPress, you can use a plugin called Picturefill.WP which allows you to implement the picture element in WordPress, without the hassle. Simply upload and embed your image as usual, and this plugin will take care of the rest.
picture element is a great addition in HTML5. We have more control over the image size and dimension that the browser should present. And with picturefill we can use this new element right now even though no browsers have implemented it yet. Picturefill works in a wide range of browsers including in IE (albeit with a few caveats).
Lastly, see the demo and download the source code below.