The new srcset and sizes explained

Uses picture/srcset/sizes polyfill picturefill 2.

There are now two responsive images solutions which can be combined or used on their own. This article focuses on the simpler one, which will do for almost all responsive content images, which aren’t art directed and should just stretch and squish with max-width: 100%;.

Until now we used media queries to determine which size the viewport is and which pixel density the screen has and load a specific source according to that. With srcset we don’t need that anymore.

We don’t tell the browser which source it should display at which screen size and pixel density, because that is inflexible and lead to dozens of lines of code and definitions just for one single image. Even worse, it’s not really future proof and we only support pixel densities that we defined. What if a 4x screens comes along tomorrow? Did you write media queries to support that? I haven’t. But with srcset we are covered.

What we do with srcset and sizes is, we tell the browser which sources, aka files, it has at its disposal and which width they have. Then we also tell the browser how wide the image should be displayed at any given viewport width. The browser now knows everything it needs to know to decide which image is appropriate to use. I like to imagine the img tag as a container. We as developers only define how big the container should be at any given point and the browser decides which source to load to get the best output for the user.


<article>
    <img srcset="large.jpg 1400w, medium.jpg 700w, small.jpg 400w"
         sizes="(min-width: 700px) 700px, 100vw"
         alt="A woman reading">
</article>>

* {
    margin: 0;
    padding: 0;
}

article {
    margin: 0 auto;
    max-width: 700px;
}

img {
    max-width: 100%;
}

source

Leave a Reply

Your email address will not be published. Required fields are marked *