Learn

Specificity is the order by which the browser decides which CSS styles will be displayed. A best practice in CSS is to style elements while using the lowest degree of specificity so that if an element needs a new style, it is easy to override.

IDs are the most specific selector in CSS, followed by classes, and finally, type. For example, consider the following HTML and CSS:

<h1 class='headline'>Breaking News</h1>
h1 { color: red; } .headline { color: firebrick; }

In the example code above, the color of the heading would be set to firebrick, as the class selector is more specific than the type selector. If an ID attribute (and selector) were added to the code above, the styles within the ID selector’s body would override all other styles for the heading.

Over time, as files grow with code, many elements may have IDs, which can make CSS difficult to edit since a new, more specific style must be created to change the style of an element.

To make styles easy to edit, it’s best to style with a type selector, if possible. If not, add a class selector. If that is not specific enough, then consider using an ID selector.

Instructions

1.

To compare type, class, and ID specificity, let’s add a class and ID to an existing element.

On line 12 of index.html, there is an <h5> element with the author’s name. Give the element a class of author-class and an ID of author-id.

2.

The element now has 3 ways of selecting it, by type, class, and ID. Add the 3 following rulesets to the bottom of style.css utilizing each of the selectors:

h5 { color: yellow; } .author-class { color: pink; } #author-id { color: cornflowerblue; }

Each of these rules selects the same element in a different way. Which style will win the “specificity war”? Click “Run” to find out!

Because ID is the most specific selector, the element will change to cornflower blue. You may have noticed the other <h5> elements changed to yellow. This is because the most specific (and only) selector they have is their type.

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?