CSS Specificity Hierarchy and Overriding !important Flag in CSS

Photo by Hamed Daram on Unsplash

CSS Specificity Hierarchy and Overriding !important Flag in CSS

ยท

2 min read

Alright, let's say you have different CSS stylings applied to the same HTML element through different selectors. For example, something like this:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS Specifity</title>
  <style>
    p {
      color: green;
    }

    .myP {
      color: yellow;
    }

    #myP {
      color: red;
    }
  </style>
</head>

<body>
  <p class="myP" id="myP" style="color: blue">CSS Specificity Hierarchy</p>
</body>

</html>

What would be the color of the CSS Specificity Hierarchy text displayed in the browser?

Answer
It's "blue"

Browsers have algorithms to decide which CSS declaration is the most relevant to an HTML element. Therefore, through multiple CSS selectors like in the above code, the CSS Specificity Hierarchy would have the color blue since it is decided to be the most relevant to the element.

Sources to Learn

Each of the CSS selectors has weight points that going to be calculated by the browser. You can see it as a prioritization point. The bigger the point, the higher it will be prioritized. Here are a few sources that I think explain it well:

Overriding !important flag

After reading articles on CSS specificity, you might find that the only way to override inline styling is through the !important flag. But the !important flag itself is an exception to the CSS specificity rule. To quote from MDN:

If declarations from the same origin and cascade layer conflict and one property value has the !important flag set, the important declaration is applied no matter the specificity.

But with an understanding of CSS specificity, we can override a declaration with the !important flag. If there are numerous conflicted declarations each with an !important flag, then the declaration with higher CSS specificity is applied.

Therefore, if you want to override this:

p {
    color: red !important;
}

You can do it like this:

p {
    color: red !important;
}

#myP {
    color: green !important;
}

I found a great Stack Overflow answer to this here.


That is all for this one. This one is a bit random.

Cheers ๐Ÿป

ย