Cascading of CSS Rules

As I previously mentioned in one of my other posts, for educational purposes, you may comingle and use inline styling, with internal styling and external styling. However, in private industry and as a best practice measure you should only use external styling. With that said, if you do use all three stylings, you should understand how conflicts between rules are resolved. In other words, if there are two or more rules that apply to the same element or tag, it is important to understand which will apply or take precedence. Before you can determine that, you must know some basic CSS rules.

Last Rule

The last rule states that if two selectors are identical, the latter of the two will take precedence. In the example listed below, the background color for the paragraph element will be red because the last rule is the one that applies.

P{
    background-color: blue;
}

P {
    background-color: red
}

Rule of Specificity

If there is a conflict between two rules where two selectors are selecting the same element or tag, the selector with the more specific selector will have precedence over the other. In the example below, the universal selector is selecting everything and styling it with a red background, however the paragraph selector is also selecting paragraphs and styling it wit a blue background. Is the paragraph element going to have a red background or a blue background? The answer is blue. Why blue? Because the “P” selector is more specific of a selector than the universal selector. Actually, the universal selector is not specific at all. It pics all the elements on a page.

* { 
    background-color: red;
}

P {
    background-color: blue;
}
---html----
<p id="test">Testing</p>

CSS Keywords

In order to override any predetermined rules in CSS, you could use the keyword !important after any property value to indicate that a rule that otherwise would not be as important is now more important because it has the keyword !important after the declaration. keep in mind that the !important keyword must be used for each declaration that you want to declare as more important.

Using the example below, normally the rule of specificity would state that the paragraphs would be blue because the selector is more specific. However, by adding the !important keyword, we are breaking the rule of specificity for that declaration.

* { 
    background-color: red !important;
}

P {
    background-color: blue;
}
---html----
<p id="test">Testing</p>