CSS Custom Properties and !important

💁‍♂️ In this post, I’m taking my own spin on a post originally by Stefan Judis. Doing so, it helped me to better grasp it myself and I was also able to simplify the examples. I hope you will find it helpful too.

What happens when you set !important on a Custom Property? Stefan Judis dug into the subject and posted about it. It all starts with this interesting paragraph from the specification:

Custom properties can contain a trailing !important, but this is automatically removed from the property’s value by the CSS parser […]

As an example, take this snippet:

div {
  --color: red !important;
  background: var(--color);
}

div {
  background: yellow;
}

Under normal circumstances, red !important would win from yellow. But since !important gets removed (because it is used in a Custom Property) the snippet basically boils down to this:

div {
  background: red;
}

div {
  background: yellow;
}

As both selectors live in the same Origin and have the same Specificity, it’s “Order of Appearance” that determines the winner: the last declaration wins, i.e. background: yellow;

~

This doesn’t mean that !important is entirely discarded in combination with Custom Properties though. The modifier does get used, but only when trying to determine the actual value for that Custom Property if you have multiple competing declarations.

div {
  --color: red !important;
  background: var(--color);
}

.class {
  --color: blue;
}

Although the .class selector is more specific than the div selector, the resulting value for --color will be red. This is because the !important made it win.

~

When the resulting value gets used in the background property, the !important part will, as per spec, be removed again.

This means that when combining both snippets …

div {
  --color: red !important;
  background: var(--color);
}

.class {
  --color: blue;
}

div {
  background: yellow;
}

… the result will again be yellow because we end up in the same situation as in the first example:

  • For the Custom Properties, red !important will win from blue
  • When used, (the flattened) background: red; will lose from background: yellow; because both selectors live in the same Origin, have the same Specificity, and background: yellow; is declared later.

Here’s a CodePen demo for you to play with:

See the Pen
Custom Properties vs !important
by Bramus (@bramus)
on CodePen.

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.