This content originally appeared on Geoff Graham and was authored by Geoff Graham
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
- Using Performant Next-Gen Images in CSS with image-set (Ollie Williams, CSS-Tricks)
- A Complete Guide to CSS Functions (Eric Bailey, CSS-Tricks)
- CSS Image Values and Replaced Content Module Level 4 (W3C specification)
The post How to use serve optimized CSS background images based on screen resolution appeared first on Geoff Graham.
This content originally appeared on Geoff Graham and was authored by Geoff Graham
Geoff Graham | Sciencx (2021-07-06T12:28:00+00:00) How to use serve optimized CSS background images based on screen resolution. Retrieved from https://www.scien.cx/2021/07/06/how-to-use-serve-optimized-css-background-images-based-on-screen-resolution/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.