Did you know that CSS Custom Properties can handle images too?

Avatar of Robin Rendle
Robin Rendle on

Find and fix web accessibility issues with ease using axe DevTools Pro. Try for free!

So you might be aware of CSS Custom Properties that let you set a variable, such as a theme color, and then apply it to multiple classes like this:

:root {
  --theme: #777;
}

.alert {
  background: var(—-theme);
}

.button {
  background: var(—-theme);
}

Well, I had seen this pattern so often that I thought Custom Properties could only be used for color values like rgba or hex – although that’s certainly not the case! After a little bit of experimentation and sleuthing around, I realized that it’s possible to use Custom Properties to set image paths, too.

Here’s an example of that in action:

:root {
  --errorIcon: url(error.svg)
}

.alert {
  background-image: var(--errorIcon);
}

.form-error {
  background-image: var(--errorIcon);
}

Kinda neat, huh? I think this could be used to make an icon system where you could define a whole list of images in the :root and call it whenever you needed to. Or you could make it easier to theme certain classes based on their state or perhaps in a media query, as well. Remember, too, that custom properties can be overridden within an element:

:root {
  --alertIcon: url(alert-icon.svg)
}

.alert {
  background-image: var(--alertIcon);
}

.form-error {
  --alertIcon: url(alert-icon-error.svg)
  background-image: var(--alertIcon);
}

And, considering that custom properties are selectable in JavaScript, think about the possibilities of swapping out images as well. I reckon this might useful to know!