šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

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.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


Leave a Reply

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