CSS custom properties for image backgrounds explained
Normal background colour
Mostly we might use a custom CSS property for a solid or even gradient background like this:
In the code above we use the same variable for both light section and the button. We use its normal colour for the light section. But for the button we changed the variable value to another colour and then assign that as the button background. A neat approach we could use with CSS custom properties.
Image as a background
Additionally we could use CSS variables for image backgrounds. Here is a pen I created to demonstrate this:
Basically we use the same technique. But this time we assign the image url to a CSS variable:
--imageBg: url("image1.jpg") no-repeat;
margin: 10px auto;
--imageBg: url("image2.jpg") no-repeat;
This is very useful incases like icons or SVGs where we need to change images per request. Use cases like hover over or click events could be some of the examples to switch between image backgrounds using CSS custom properties.
Thank you for reading.