CSS Specificity

CSS Specificity determines what CSS rule should be applied in the browser. It is common belief that rules have higher priority if they are declared further down in the CSS file. This is not always the case. Consider the following code below.

<div class="drinks">
    <ul id="list">
        <li class="highlighted">Cola</li>

:et’s assume that the following rule within a CSS file is in place.

#list .highlighted {
    color: blue;

And you want to change the text colour of your highlighted drink to red. To do thism you might add the following rule.

.highlighted {
    color: red;

You may notice that the highlighted text did not change to red. So why is this? This is where specificity comes in.

Within CSS, every selector has its place in the specificity hierarchy. If two selectors apply to the same element, the one with higher specificity wins.

So in the above example, the #list ID selector has higher priority than the .highlighted class selector. A simple overview of the priorities from highest to lowest can be seen below.

  • Style attributes
  • ID selectors
  • Class, pseudo class and attribute selectors
  • Element selectors

So to add an overriding CSS rule to the above example, you could use the code below.

.drinks #list .highlighted {
    color: blue;

When an !important rule is used on a style declaration, this declaration overrides any other declarations and takes the highest priority.

.highlighted {
    color: red !important;

Whilst it is not recommended to use !important, it might be used when have to override inline styles on elements themselves.

It is recommended to take a look at cssspecificity.com which provides an easy to understand overview of CSS Specificity and priorities of selectors.