A few day ago my colleague ask me to help him with a CSS problem. Even though he specified one element precisely the style definition takes no affect. I told him that CSS is based on a mathematical system. At the time I didn’t know that this underlaying layer is called CSS Specificity. Within this article I will take a closer look on that system.
Everyone that has to handle CSS files knows the problem. You’re creating a definition, but nothing happen. You change the definition. Also no affect. You keep on trying and trying until the point of time that it works or you’re feed up with the CSS definitions. Thereby the solution is just one thought away. Once understand the principles of CSS Specificity is’t pretty easy even to handle very huge CSS files. But how does that promised system works in detail?
Specificity a.k.a. Priority
Every definition gets points. The following list shows how these points are distributed:
- elements: 1 point
- class: 10 points
- id: 100 points
- in line style: 1000 points
So far about the theory. I personally understood the systeme at the time I was doing some practical tests. Therefore I provide some practical examples as well.
Examples
- a: 1 point (1 element)
- a.active: 11 points (1 class + 1 element)
- li a: 2 points (2 elements)
- li a.active:hover: 13 points (1 classes + 3 elements)
- #content li a:active: 112 points (1 id + 1 class + 2 elements)
- <hr style=”color:red” />: 1000 points (1 in line style)
no comment untill now