CSS Selectors and Specificity

If the embed above does not work here is a link to the full version of the video

We’ve seen that we use HTML to markup content, to give that content structure and meaning, and that we use CSS to style and present the content.

We’ve seen that we can use different CSS selectors to target the HTML elements that we want particular CSS rules to apply to. It is actually possible to write multiple CSS rules that all target the same element. For example, if we have a webpage with the following content:

<p class="warning"></p>

and a CSS file with the following rules:

p {
color: red;
}

.warning {
color: blue;
}

Which CSS declaration will be applied to our code? How does a web browser work out which rules to apply and which to ignore?

There are a couple of processes that help the browser determine which rules to apply. Firstly, CSS files are read from top to bottom. Rules that are further down in the file overwrite rules that are closer to the top. So, for example, if we have a webpage with the following content:

<p class="warning">here is some text</p>

and a CSS file with the following rules:

p {
color: red;
}

p {
color: blue;
}

The text in the paragraph will end up blue, as the second rule overwrites the first as it is further down in the style sheet. You can see this example below:

See the Pen CSS Order by Martin Chorley (@martinjc) on CodePen.

However, the order is not the only thing that determines which rules should apply. There is also the concept of ‘Specificity’.

Specificity

Specificity is the mechanism that allows Web Browsers to determine which CSS rule should be applied to an element. The rules for specificity are simple to follow.

For each CSS selector that matches a given HTML element:

The values are added together, and the rule with the highest specifity is the one that is applied to the element.

CSS Selectors and Specificity Demo

If the embed above does not work here is a link to the full version of the video

Code Examples

There are a set of code examples that accompany this course showing the use of the fundamental HTML tags and CSS styles/rules that we look at. (Right click and open in a new window/tab) if you’re viewing this on Learning Central.