This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
I love custom CSS properties. They're flexible, make CSS more DRY ("don't repeat yourself"), and can keep a CSS codebase maintainable. The larger a CSS codebase, the more critical your CSS is easy to handle. CSS can become messy quickly, especially the use of !important
often results in a maintenance nightmare.
I avoid !important
as much as possible, and that's why I've never thought of using it in custom properties. Today I learned that !important
can be defined as a custom property value.
Be warned, though, the !important
keyword defined in a custom property value behaves differently than you think!
The syntax for custom property values is permissive. The specification allows everything but a few specific tokens as the custom property value. These prohibited tokens include unmatched ]
or }
, semi-colons or the !
character.
Even though !important
obviously includes a !
, it's considered a special case that works "just fine"!
As you see in the example above, the color
property is parsed and applied correctly. That's great news, but be aware that !important
in custom property values comes with surprising behavior.
If you have another look at the spec, you'll find this note.
Custom properties can contain a trailing !important, but this is automatically removed from the property’s value by the CSS parser, and makes the custom property "important" in the CSS cascade.
!important
is stripped off the property value? Does that mean you can overwrite an "important CSS custom property"? Jup, it does!
But the spec defines that the property is marked "important" in the CSS cascade; what's that about then?
The CSS cascade comes into play when multiple custom property definitions apply to the same element.
In the above case, the custom property with the highest specificity (the !important
one) is applied. But it remains that !important
is not set as a property value. You can still overwrite an "important CSS property" with another CSS property definition easily.
I stand by it: it's best to avoid !important
and if you really have to use it, consider it very carefully. And honestly, I wouldn't mix !important
into custom property values because this surprising "quirk" is very hard to spot!
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
Stefan Judis | Sciencx (2021-11-29T23:00:00+00:00) The surprising behavior of "important CSS custom properties" (#tilPost). Retrieved from https://www.scien.cx/2021/11/29/the-surprising-behavior-of-important-css-custom-properties-tilpost/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.