CSS Specificity & Me, a Love-Hate Relationship

In the past couple of projects I’ve worked on for my grad school projects, I’ve run into frustrating issues with tiny elements of my webpages. I get to a point where I want to throw my laptop across the room, or fantasize about the damage I could to to it with a solid Louisville Slugger. Usually, I have to walk away, regroup, and/or call a classmate for help. And both times it was an issue with my CSS specificity.

While I have been playing with CSS for a year now, I somehow was still struggling with being so very specific. It just wasn’t clicking until I got in touch with The Force. Okay, it wasn’t that exact part of a Smashing Magazine article titled “CSS Specificity: Things You Should Know.” It was mostly the introduction to the calculations.

The theory behind it is giving everything a value. The values are based as such:

specificity-calculationbase

In even more detail, the number assignments are as follows:

1 * { } 0
2 li { } 1 (one element)
3 li:first-line { } 2 (one element, one pseudo-element)
4 ul li { } 2 (two elements)
5 ul ol+li { } 3 (three elements)
6 h1 + *[rel=up] { } 11 (one attribute, one element)
7 ul ol li.red { } 13 (one class, three elements)
8 li.red.level { } 21 (two classes, one element)
9 style=”” 1000 (one inline styling)
10 p { } 1 (one HTML selector)
11 div p { } 2 (two HTML selectors)
12 .sith 10 (one class selector)
13 div p.sith { } 12 (two HTML selectors and a class selector)
14 #sith 100 (one id selector)
15 body #darkside .sith p { } 112 (HTML selector, id selector, class selector, HTML selector; 1+100+10+1)

(Did you see The Force at work in there?)

So, using some more borrowed graphics from Chris Coyier in his article “Specifics on CSS Specificity” for the web resource CSS-Tricks.com, it becomes clearer what takes precedence over what.

cssspecificity-calc-1

cssspecificity-calc-1 cssspecificity-calc-5

Being a visual person, somehow the #, ., and : all started falling into place.

In Coyier’s words:

  • If the element has inline styling, that automatically1 wins (1,0,0,0 points)
  • For each ID value, apply 0,1,0,0 points
  • For each class value (or pseudo-class or attribute selector), apply 0,0,1,0 points
  • For each element reference, apply 0,0,0,1 point

You can generally read the values as if they were just a number, like 1,0,0,0 is “1000”, and so clearly wins over a specificity of 0,1,0,0 or “100”. The commas are there to remind us that this isn’t really a “base 10” system, in that you could technically have a specificity value of like 0,1,13,4 – and that “13” doesn’t spill over like a base 10 system would.

Even a non-math, journalism major who was convinced to take “Math Fundamentals” – Venn Diagrams and all –upon entering college, I can get this. I won’t say I’m necessarily an expert, but I am a lot closer to getting there.

 

Leave a Comment