Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Serving better background images with image-set in CSS

The image-set() function in CSS is intended to work with the background-image property and can be used to achieve 2 main goals:

  1. provide a different background image, based on the screen pixel density. Something like srcset, but for background images:

    .hero-element {
    background-image: image-set(
        "hero-small-res.jpeg" 1x, 
        "hero-big-res.jpeg" 2x);
    }
  2. or to serve advanced file formats for background images and replacement alternatives if that format is not supported:

    .hero-element {
    background-image: image-set(
            "hero.avif" type("image/avif"),
            "hero.jpg" type("image/jpeg"));
    }
    /* in this case if the avif format is not supported,
    the jpeg file will be used */

From a browser support point of view, it is supported in all major browsers, with the amendment that for Safari you will still need to use the webkit prefix. For an extra layer of safety, you can provide a fallback alternative for it:

.element {
  background-image: url('kitten.png');
  background-image: image-set(/*...*/);
}

CSS-tricks has an interesting article it about here.