Code Highlights logo

Learn

Selectors

Specificity

In CSS, Specificity is a set of rules that dictate which styles should be applied to a particular element. It is the process of determining which styles win out when different selectors target the same element.

Specificity Hierarchy

Specificity is hierarchical. Some selectors have more weight than others. The breakdown of specificity hierarchy is as follows:

  1. Important rule
  2. ID selectors
  3. Class selectors, attribute selectors and pseudo-classes.
  4. Type selectors and pseudo-elements
  5. Universal selectors

The higher the selector is on the hierarchy, the more weight it carries, and the more precedence it gets when there is a conflict.

How Specificity Works

When there is a conflict between two or more CSS rules targeting the same element, the rule with the higher specificity will win. Consider the following example:

1#main {
2 background-color: red;
3}
4
5.container #main {
6 background-color: blue;
7}

The #main element has two styles applied from two different selectors. The first rule targets the element using the id selector, and the second targets it using a class and an id selector.

Since the ID selector has a higher specificity, the background color of the #main element will be red, not blue.


Instructions

1.

To show how specificity increases with additional selectors, let's create another ruleset with the descendant combinator and then compare it to a ruleset without.
In style.css, write a ruleset using the descendant combinator to select the <h4> elements nested in the <li> elements. Inside of the curly braces, write:

1color: orange;

Click Run and then scroll down the page to see the <h4> elements under "Here is our top list", Greece, Italy and Spain appear orange.

2.

Now, create a ruleset targeting elements with just the h4 type, and add a declaration of:

1color: green;

Will the <h4> elements turn blue? Click "Run" to find out.
The elements stay orange because there is a more specific selector for <h4> elements you wrote in the last step. Because of the more specific CSS selector (li h4), the more general selector of h4 will not take hold.

Sign up to start coding

Already have an account?

Sign In

Course content