Day 29: !important custom properties

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.


Using !important with custom properties might not work as you expect.

If you look at the following example, which color does the text have?

.example1 {
  --color: red;

  color: var(--color) !important;
  color: blue;
}
Show .example1
I'm red!

Makes sense! By using !important we make the first color declaration more important than the second one.

Now, what about this? Which color does the text have now?

.example2 {
  --color: red !important;

  color: var(--color);
  color: blue;
}
Show .example2
I'm blue!

In order to understand that, we have to look at the spec. There it says:

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

Aha! It's okay to use it, but it will be removed from the value by the parser, and since it's removed, the second color declaration overwrites the first one.

Why can we use it, if the CSS parser removes it anyway? Well, because the sentence continues:

…and makes the custom property "important" in the CSS cascade.

Custom properties are just like ordinary properties in CSS part of the cascade and they follow its rules. If you take the following example, which color does the text have?

.example3 {
  --color: red;
  --color: blue;

  color: var(--color);
}
Show .example3
I'm blue!

Why? Because declarations defined later in the document overwrite those defined earlier, if they have the same specificity. This applies to custom properties just like it does to ordinary properties.

We can change the specificity in CSS by using different selectors or by making a property !important.
With that in mind, can you guess which color the text has in the following example?

.example4 {
  --color: red !important;
  --color: blue;

  color: var(--color);
}
Show .example4
I'm red!

I'm sure you got that one right! One last example, to conclude this topic. Which color does the text have?

.example5 {
  --color: red !important;
  --color: blue;

  color: var(--color);
  color: blue;
}
Show .example5
I'm blue!

This post is based on a chapter in an article written bei Temani Afif.

See on CodePen

Further reading

Overview: 100 Days Of More Or Less Modern CSS