Responsive Images in CSS


Srcset in CSS

<img srcset="
  examples/images/image-384.jpg 1x, 
  examples/images/image-768.jpg 2x
" alt="">

One image for 1x displays, a larger image for 2x displays. If we wanted to do that same thing, only as a background-image in CSS, we could do:

.img {
  background-image: url(examples/images/image-384.jpg); 
}
@media 
  (-webkit-min-device-pixel-ratio: 2), 
  (min-resolution: 192dpi) { 
  .img {
    background-image: url(examples/images/image-768.jpg);
  }
}

There is another way as well, that is actually closer to how srcset works, and that’s using the image-set() function in CSS:

.img {
  background-image: url(examples/images/image-384.jpg);
  background-image: 
    -webkit-image-set(
      url(examples/images/image-384.jpg) 1x,
      url(examples/images/image-768.jpg) 2x,
    );
  background-image: 
    image-set(
      url(examples/images/image-384.jpg) 1x,
      url(examples/images/image-768.jpg) 2x,
    );
}

picture in CSS

<picture>
  <source srcset="extralarge.jpg" media="(min-width: 1000px)">
  <source srcset="large.jpg" media="(min-width: 800px)">
  <img srcset="medium.jpg" alt="">
</picture>
<picture>
  <source srcset="large.jpg, extralarge.jpg 2x" media="(min-width: 800px)">
  <img srcset="small.jpg, medium.jpg 2x" alt="">
</picture>

For more details: https://css-tricks.com/responsive-images-css/