Day 41: custom properties and url()s

posted on

It’s time to get me up to speed with modern CSS. There’s so much new in CSS that I know too little about. To change that I’ve started #100DaysOfMoreOrLessModernCSS. Why more or less modern CSS? Because some topics will be about cutting-edge features, while other stuff has been around for quite a while already, but I just have little to no experience with it.

Let’s say you want to swap the background image of an element based on a certain condition, like whether it’s pressed, using custom properties.

button {
  --background-image: "/not-pressed.svg";
  background: url(var(--background-image));

button[aria-pressed="true"] {
  --background-image: "/pressed.svg";

This looks fine, but it doesn't work because var(--background-image) contains invalid characters. The reason the argument is invalid is that url() works both with quotes url("image.svg") or url('image.svg') and without quotes url(image.svg). By passing a value without quotes you're not passing a string to a CSS function, but you're creating an url-token and this token expects a certain format that requires characters like ( to be escaped.
That's a very abbreviated explanation. For details, please read “Why custom properties don't work with the url() CSS function” by the amazing Stefan Judis.

To work around that issue, you have to move the url() function into the value of the custom property.

button {
  --background-image: url("/not-pressed.svg");
  background: var(--background-image);

button[aria-pressed="true"] {
  --background-image: url("/pressed.svg");

See on CodePen

Further reading

Do you want to learn even more awesome CSS?

I'm running a workshop with my friends at Smashing Magazine in which I introduce you to the most useful modern features in CSS and show how you can implement them today in your code base to improve scalability, maintainability, and productivity.

Learn more about the workshop!

Overview: 100 Days Of More Or Less Modern CSS