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 *

Home Screencasts Best of Newsletter Search X

📖 50 Javascript, React and NextJs Projects

Hi friend! Before you go, just wanted to let you know about the 50 Javascript, React and NextJs Projects FREE ebook.

One of the best ways to learn is by doing the work. Choose from 8 project categories and get started right away:

  • Business & Real-World
  • Games & Puzzles
  • Fun & Interesting
  • Tools & Libraries
  • Personal & Portfolio
  • Project Add-Ons
  • Productivity
  • Clones

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects complete with project briefs and wireframes!

Keep building and level up! Get all projects as an ebook right to your inbox!

X