NetFire

NetFire United States
Call us: 855-MY-NETFIRE (696-3834)

Creating Responsive Images

Web users browse the internet in many ways – desktop computers, tablets, mobile phones, and more. Developers can accommodate many of these by using media queries to adjust the layout of pages, but you’re probably wondering how to do the same with images. This tutorial explains how to create responsive images that adjust to different devices, letting you deliver the correct image to the correct device.

Features such as srcset attributes and width descriptors let web developers deliver an appropriate image to each user depending on a variety of conditions like screen size, viewport size, screen resolution, and more. To make sure these new pieces of HTML work in old browsers, we can include a piece of JavaScript known as a polyfill – this way, newer browsers that natively support the new HTML (e.g. Chrome) can implement them as usual, and older browsers that don’t support the new HTML can simply use the polyfill. In this tutorial, we’ll be using a polyfill called Picturefill, and will work with .jpg images. You can download the minified version of Picturefill online. The file, picturefill.min.js, should end up in the Javascript folder that exists in the same directory that holds your HTML files, organized like so:

responsive images

 

In the images folder depicted here, the ending of the filenames describes the resolution or width of the photo – 1x, 2x, small, medium, and so on.

Add the Picturefill polyfill to your HTML in the head, along with an async attribute. The async attribute improves performance by making the browser load the script asynchronously.:

Note: You can only add the async attribute to scripts that have no dependencies – for instance, you can’t add it when loading a plugin that depends on jQuery being present first.

Using srcset

You can use the srcset attribute in images on your page, like so:

<img

     srcset=”img/photo-2x.jpg 2x,

             img/photo-1x.jpg 1x”

     src=”img/photo-1x.jpg”

/>

The 1x portion of srcset is a pixel density descriptor. Now, your image will adjust according to the device used to view it.

Using width descriptors

You can also use width descriptors on your page, like so:

<img

     srcset=”img/photo-large.jpg 1500,

             img/photo-medium.jpg 1000,

             img/photo-small.jpg 500”

     src=”img/photo-medium.jpg”

/>

Now, the browser can select the correct width at which to display your image.