Understanding CSS Specificity

corybolles
by corybolles
Understanding CSS Specificity

CSS Specificity is the set of rules within CSS that determine which styles will be applied to an element, and which will not. Take the following example:

Imagine you create a web page with several paragraphs of text. One of these paragraphs has several attributes on it, including the CSS class "red-text" and the CSS ID "first-paragraph".

Now, imagine that the following CSS is loaded on the page:

#first-paragraph {
  color: blue;
}

.red-text {
  color: red;
}

What color will the paragraph be? Will it follow the ID rule and be blue, or the class rule and be red? This is where CSS specificity comes into play.

In this case, the paragraph will be blue. This is because an ID selector takes priority over a class selector. Classes and IDs both take priority over a plain element selector.

Inline CSS takes priority over any rule, except when it has an !important exception.

Understanding !important

In CSS, we have something called the !important exception. Essentially, you can override a CSS rule that has a higher specificity by adding. "!important" after the value and before the semi-colon. This is generally considered bad practice however, as it makes debugging CSS code very difficult because it disrupts the natural cascading effect of the styles.

We always do our best to abide by the following rules regarding using !important.

  1. Do your best to find a CSS solution that doesn't use the !important rule.
  2. Only ever use !important if the CSS you need to override is from an external file that you can't edit. If it's not, there's a way to override the style without the rule.
  3. Finally, never use the rule on a stylesheet that is site-wide. The !important rule should be used sparingly - only on page specific styles

Below is an example of using the !important exception to override a CSS rule.

#first-paragraph {
  color: red;
}

p {
  color: blue !important;
}

Without the !important rule, the above code will make all <p> elements blue, except for the one with the #first-paragraph ID, which will be red. With the !important rule, all paragraphs will be blue regardless of their ID.

 

With an understanding of CSS Specificity under our belts, let's move on to discuss making more advanced selections in CSS so that we don't have to use the !important rule.

Previous Lesson Next Lesson

Leave a Reply

Your email address will not be published. Required fields are marked *

crossmenu linkedin facebook pinterest youtube rss twitter instagram facebook-blank rss-blank linkedin-blank pinterest youtube twitter instagram