CSS Specificity

Specificity is a weight given to each CSS rule that determines which one gets applied by the browser.   This is an important concept to understand when you are trying to figure out why your awesome new stylesheet is getting overridden.


Specificity Chart

specificity.png

Inline styles

<!-- Specificity 1000 -->
<h1 style='color:orange'>Heading</h1>

Inline styles are considered bad practice because you mix the content and presentation in the same file.  

IDs

/* Specificity 0100 */
#content { color: orange; }

Use ID selectors to increase the specificity whenever possible.

Classes, attributes, and pseudo-classes

/* Specificity 0010 */
.success { color: green; }

Elements and pseudo-elements

/* Specificity 0001 */
h1 { color: red; }

/* Specificity 0011 */
div.success { color: green; }

The cascading nature of CSS means that it is read top to bottom.    If multiple rules apply to the same element AND have the same specificity, then the last one is applied:  

/* Specificity 0001 */
h1 { color: green; }

/* Specificity 0001 */
h1 { color: red; } /* last one wins */

When there are rules with different specificity values, the highest value wins:

/* Specificity 0001 */
div { color: green; }

/* Specificity 0011 */
div.navigation { color: blue; } /* highest value wins */

/* Specificity 0002 */
div a { color: red; }