CSS cascading order of precedence

CSS means cascading style sheet. What the cascading mean? It means the styles provided in a document are cascaded. You can import as many style sheets as you want in a document, all of they can have their own style declarations on any element, each definition has an order of precedence, finally, after computing of the precedences, a computed style declaration is generated and then is applied on to the elements. The process of determining of the final style sheets is called cascading.

The computation process follows some simple rules.

The styles defined in element as style property has the highest priority. This is useful for debugging, when you edit it, the effect is immediately visible. The styles defined later in style sheet file or internal style sheet has the higher priority. The browser read and parse CSS style declaration one by one in the order of their appearance. The default styles defined by browser has the lowest priority. This what a page will looks like when no CSS are provided.

Sometimes you may want to apply a style in CSS file but it didn't work, maybe you are editing a complex style sheet file written by others or get lost in the complex order of precedences, you can use !important to forcefully change the priority of a style. Editing style property can do this too, but its never a good idea to write the style directly on element for non-debugging purposes.

Here is an example

 
p {
    font-size: 12px !important;
}
 

Unexpected CSS precedence problem

In most cases, the priority is easy to identify, just follows the rules mentioned above, but there are cases the priority is not so clear. Let's see an example

Here is a document

 
<html>
<head>
  <style>
    h1 {
        color: red;
    }
 
    .entry-title {
        color: blue;
    }
  </style>
</head>
<body>
  <div class="content">
    <h1 class="entry-title">Hello</h1>
  </div>
</body>
</html>
 

The color is blue.

You might think the reason is the .entry-title is defined after the h1 style definition.

If we change it to this

 
<html>
<head>
  <style>
    .content h1 {
        color: red;
    }
 
    .entry-title {
        color: blue;
    }
  </style>
</head>
<body>
  <div class="content">
    <h1 class="entry-title">Hello</h1>
  </div>
</body>
</html>
 

It becomes red.

The reason is specificity, unlike the general rules and !important property, the biggest problem of the specificity is they are not so easy to identify at a glance. The rule of style specificity is more complex and subtle.

See details CSS rule priority and specificity