News & UpdatesProgrammingWeb programming Store My Projects
Links
Affiliates

CSS Tutorial – 09 – Specificity

CSS tutorials

When several rules apply to the same element, and they have conflicting properties, there is a priority scheme to determine which rule is the dominant one. If the selectors are the same the property declared last will be the one that counts. Otherwise, the more specific one will win out.

p { color: orange; } /* overridden */
p { color: silver; } /* dominant */

To calculate the specificity there are some basic rules. The universal selector has the lowest specificity with the weight 0.

* { color: red; } /* 0 */

The element selectors have the weight 1.

p { color: blue; } /* 1 */

So a selector containing two element selectors will have a specificity of 2.

body p { color: gold; } /* 2 */

A class selector has the weight 10 and so does pseudo classes and attribute selectors. Because they also include an element selector they will have a total weight of 11. The pseudo elements do not count for any specificity, according to the CSS specification.

.a { color: lime; } /* 10 */
p:first-child { color: navy; } /* 11 */
p[class=a] { color: teal; } /* 11 */

ID selectors have a weight of 100.

#i { color: aqua; } /* 100 */

Inline styles have a weight of 1000.

<p style="color: black; /* 1000 */">Text</p>

To override all other conflicting rules a rule can be declared as !important.

p { color: red !important; }

Note that the actual weight of attribute selectors, pseudo element, and classes varies slightly between different browsers.

Recommended additional reading:
Sams - Teach Yourself HTML and CSS in 24 Hours