Cascading Style Sheet

The word "cascading" in the name Cascading Style Sheets refers to the way that styles cascade from various style sheet sources to the elements in the document tree. The CSS cascade is the process of resolution that determines the final value of a property when multiple applicable declarations exist for that property.

Specificity and Precedence

Specificity is a mechanism within the CSS cascade that aids conflict resolution. The concept of specificity states that when two or more declarations that apply to the same element, and set the same property, have the same importance and origin the declaration with the most specific selector will take precedence.

Selector Type 1 2 3 4
Element Types and Pseudo-elements 0 0 0 1
Classes, Attributes, and Pseudo-classes 0 0 1 0
IDs 0 1 0 0
Inline Style 1 0 0 0

Example 1: table th {color:red;} - calculetes as 0,0,0,2 (seq of 2 elements).

Example 2: table tr .myclass {color:red;} - calculates as 0,0,1,2 (seq of 2 elements + class).

Example 3: #myId td {color:red;} - calculates as 0,1,0,1 (seq of an element + ID).

Example 4: <tr style="color:red;"> - calculates as 1,0,0,0 (inline style).

Attention: specificity of 1,0,0,0 is greater than one of 0,100,100,100 and specificity of 0,0,1,3 is greater than one of 0,0,1,1.

Example:
Markup: <body class="tundra"><div id="abc"><span class="ccc">Content...
CSS:
#abc span {color:green}
.tundra div .ccc {color:red}
The content will be green: 0,1,0,1 against of 0,0,2,1.

Attention: as you can see, an inline style rule will always have a specificity of 1,0,0,0 - the highest level of specificity. The only way to overwrite them within the CSS cascade is to use the !important on the relevant declarations - an approach that creates a maintenance nightmare. A style sheet that's littered with important declarations often signals that an author hasn't thought clearly enough about the structure of the CSS.

The order of including the CSS files into a Web Page is very important! See next page.