!important and CSS Custom Properties

Chris Coyier Chris Coyier on

This just bit me the other day so I’m going to write it down. Again, as it’s surprised me before. I just think I can maybe explain it even more clearly this time.

CSS custom properties are super permissive in what values are valid. Like this is totally fine, and I sure it can get much weirder:

--whats-up: (👍🏻ᴗ _ᴗ)👍🏻;Code language: CSS (css)

So my brain extends that to think that this also is a complete valid value:

--color: orange !important;Code language: CSS (css)

Like the value of --color is orange !important;

But it’s not! The value is just orange and the declaration itself is “important”. Hopefully this graphic makes it even more clear:

A graphic explaining CSS custom properties, highlighting the difference between the value and the declaration, with emphasis on the statement '--color: orange !important;' and clarifications in colorful text.

This can come up when there are multiple declarations that apply to the same element. Normally specificity and source order help sort out which declaration wins, but just as !important always does, an !important declaration trumps those other things.

So say you have a:

<div class="greeting">Hello</div>Code language: HTML, XML (xml)

Then two selector blocks:

div {
  --color: red !important;
}

.greeting {
  --color: blue;
  color: var(--color);
}Code language: CSS (css)

Even though --color is set to blue right there next to where it is used with a higher-specificity selector, the greeting will actually be red. If !important became part of the value, blue would have won because the custom property declaration is more specific and would have won. But it’s the custom property declaration itself that is important-ized and thus the red value wins.

Wanna learn modern CSS layout?

Frontend Masters logo

We have an in-depth course on Advanced CSS Layouts that digs into the big stuff like grid and flexbox, and then more like custom properties and calc(), using them for advanced layouts and practical solutions.

Leave a Reply

Your email address will not be published. Required fields are marked *

$916,000

Frontend Masters donates to open source projects through thanks.dev and Open Collective, as well as donates to non-profits like The Last Mile, Annie Canons, and Vets Who Code.