In my previous post I explained how css selection works. However what happens when a property of an element is defined multiple times? Which one will be used?
Take for example the following html:
<html> <head> <title>test</title> </head> <body> <h1>Header</h1> <p>Line of text</p> <p>Another line of text</p> <div class="special"> <p>Special line of text</p> </div> </body> </html>
If we have the following css line:
p { color: red; }
The color of all p elements will be red
If we have the following css lines:
div.special p { color: blue; } p { color: red; }
The p inside the div with class “special” will be blue while the other p elements will still be red. This is because “div.special p” is more specific then the “normal” p selector.
If we have the following css lines:
p { color: red; } p { color: blue; }
The color of all p elements will be blue. This is because the blue value is more recent then the red value. Take this into account when loading multiple css files, the more recent will dominate is both are equally specific.
If we have the following css lines:
p { color: red !important; } p { color: blue; }
The color of all p elements will be red. Even though the blue property is more recent and they are equally specific. This is because the first one is marked with important. Important overrules any later changes to the specified property. This is a way to make sure a earlier property is applied in stead of a later one. This can be useful is different style sheets are loaded after your own.
With inline style, no css (except for css marked with Important) can overrule the style. This can only be overruled using JavaScript.
Inline style example:
<p style="color: orange;">This is always orange<p>
This can be overruled using the following jQuery line:
$("p").css("color","blue");
Which will add inline style to all p elements with blue as color property.
In short this is what decides which css style will dominate:
- Important suffix
- Specific
- Inline
- Id
- Class
- Element
- Most recent
Most recent will dominate if none of the others apply. More specific css will dominate over less specific css. With important this will overrule all non-important css, between multiple important css parts the most specific will eventually be dominant. The only css that cannot be overrules with css alone is inline style with the important tag applied; the only way to overrule that is by replacing is with a piece of JavaScript.