Skip to main content

CSS Specificity

Which style declaration reaches an element is decided by an algorithm called CSS specificity.

When two or more CSS rules target one element, its style comes from the rule with the highest specificity.

The examples below show this in action:

Element selector

Only one rule applies here: it makes <p> elements red, so the text is red.

Prompt
Show an HTML page with a CSS rule that sets the color of all elements to red. Include a element with the text "Hello World!" so the red color is visible.
Output: complete HTML page

Class selector

A class selector named "test" now adds a green color. The text turns green, since a class selector outranks an element selector in specificity.

Prompt
Show an HTML page with two CSS rules: a class selector ".test" with green color and an element selector "p" with red color. Include a element with class "test" and text "Hello World!" to demonstrate that the class selector wins over the element selector.
Output: complete HTML page

ID selector

An id selector named "demo" joins in. The text turns blue, since an id selector outranks both the class selector and the element selector in specificity.

Prompt
Show an HTML page with three CSS rules: an id selector "#demo" with blue color, a class selector ".test" with green color, and an element selector "p" with red color. Include a element with id "demo", class "test", and text "Hello World!" to demonstrate that the id selector wins.
Output: complete HTML page

Inline style

An inline style now sits on the <p> element. The text turns pink, since no specificity is higher than an inline style's.

Prompt
Show an HTML page with three CSS rules: an id selector "#demo" with blue color, a class selector ".test" with green color, and an element selector "p" with red color. Include a element with id "demo", class "test", an inline style of "color: pink;", and text "Hello World!" to demonstrate that the inline style wins.
Output: complete HTML page