Wednesday, October 28, 2015

How to Build Responsive Images with srcset

In this connected world where people have a variety of devices,ensuring your website works seamlessly across all of them is a need, not an option. Your website views won’t come from a single resolution device, or a single form-factor. To cater to all of them, your website needs to be responsive.

If you’re familiar with responsive web design (RWD), you probably know the intricacies that come with a responsive design (and how Bootstrap solves a lot of them!). An important part of a responsive website are responsive images. In this article, we’ll learn more about responsive images on the web and see how to build them.

What is a Responsive Image?

In simple terms, a responsive image is, depending on the device your website is being viewed, an image on that webpagedisplayed in its best form. The term ‘best form’ could mean multiple things:

  • You want to show a separate image asset based on the user’s physical screen size. For example: you want to show a separate image asset on a 13.5 inch laptop and a 5 inch mobile phone (on a maximized browser).
  • You want to show a separate image based on the resolution of the device (or, the device-pixel ratio, which is the ratio of device pixel and CSS pixel).
  • You want to show an image in a specified image format (JPEG XR, for example) if the browser supports it, probably because of the higher compression that format supports.

The building blocks for responsive are included in most modern browser including Microsoft Edge (starting Windows Insider Build 10547). You can view the Web Platform status of features like srcset here.

How to Enable Responsive Images

There are a number of ways to enable responsive behavior of images. One of the older methods (not recommended) is by simple scripting, but this leads to a couple of problems. One, if a script determines which image to download, but the script itself is loaded after the images specified in the HTML have been downloaded, you may potentially end up with two downloaded images. Two, if you don’t specify any image in HTML and want to load only the image as defined by the script, you’ll end up with no image at all for the browsers which have scripting disabled.

Hence, we need a better way to deal with responsive images. And thankfully, there is! The recommended way is to use:

  1. srcset attribute
  2. sizes attribute
  3. picture element

Let’s delve a little deeper.

Continue reading %How to Build Responsive Images with srcset%


by Saurabh Kirtani via SitePoint

No comments:

Post a Comment