1. CSS Specificity

(Approximate Time: ~ 1 hours)

One of the most important concepts to master as you start to dig into more advanced concepts in CSS, and web development in general, is Specificity. That is how the browser decides what styles to apply where. This will be key in understanding why and how different CSS naming systems and architectures are designed the way they are.

What is Specificity?

If two CSS selectors apply to the same element, the one with higher specificity wins.

 

Specificity Hierarchy

Every selector has its place in the specificity hierarchy. There are four distinct categories which define the specificity level of a given selector:

  1. Inline styles: An inline style lives within your XHTML document. It is attached directly to the element to be styled. E.g. <h1 style=“color: #fff;”>
  2. IDs: ID is an identifier for your page elements, such as #div.
  3. Classes (including attributes and Pseudo-classes): This group includes .classes, [attributes], and Pseudo-classes such as :hover, :focus, etc.
  4. Elements and Pseudo-elements: Instances such as :before and :after.

How to measure specificity?

This is a good value system to memorize for measuring specificity: Start at 0, add 1,000 for style attribute, add 100 for each ID, add 10 for each class attribute or Pseudo-class, add 1 for each element name or Pseudo-element.

For example, if you are given:

body #content .data img:hover

The Specificity value would be 122: 100 for #content, 10 for .data, 10 for :hover, 1 for body and 1 for img.

Here are a few more Specificity examples to try for yourself:

CSS Code Specificity Value
* {…} 0
li {…} 1 (one Element)
li:first-line {…} 2 (one Element and one Pseudo-element)
ul li {…} 2 (two Elements)
ul ol+li {…} 3 (three Elements)
h1 + *[rel=up] {…} 11 (One attribute and one Element)
ul ol li.red {…} 13 (one Class and three Elements)
li.red.level {…} 21 (two Classes and one Element)
style=“…” 1000 (one Inline Styling)
p {…} 1 (one HTML Selector)
div p {…} 2 (two HTML Selectors)
.sith 10 (one class Selector)
div p.sith {…} 12 (two HTML Selectors and one Class Selector)
#sith 100 (one ID Selector)
body #darkside .sith p {…} 112 (HTML Selector, ID Selector, Class Selector, HTML Selector)

 

In this video below, we cover exactly what affects CSS specificity and how to calculate the specificity of a selector through the use of multiple examples.  It is great to help you quickly comprehend all the complexities of CSS specificity.


Source: Web Dev Simplified