On July 6, 2021, I learned...

How to serve optimized CSS background images based on screen resolution

New to me, but this has been around a hot minute! I remember when the <picture> element was introduced and thinking, Wow, HTML is getting pretty darn smart. I mean, the ability to specify variations of an image and let the browser choose the most optimal file based on the user’s environment is clever, even if it’s cumbersome to write out.

<picture>
  <source media="(max-width:1000px)" srcset="picture-lg.png">
  <source media="(max-width:600px)" srcset="picture-mid.png">
  <source media="(max-width:400px)" srcset="picture-sm.png">
  <img src="picture.png" alt="picture"">
</picture>

It’s really cool that WordPress automatically handles this. Otherwise, I might never do it.

What I didn’t know is that CSS can do the same thing for background-image via the image-set() function:

.element {
  background-image: image-set( 
    "puppy.webp" type("image/webp") 1x,
    "puppy2x.webp" type("image/webp") 2x,
    "puppy.png" type("image/png") 1x,
    "puppy2x.png" type("image/png") 2x
  );
}

Again, there’s overhead making all of those images and then specifying them in CSS. But what I like about this is that thew browser will only download the image that’s used—all others are ignored. Plus, we get to use next-generation image formats in there that’s are lighter and faster for browsers that support them, as Ollie explains in his recent post. Such a nice performance win.

Resources

(Updated on 7/16/2021)

Comments are closed.