CSS Specificity is something that, until recently, I wasn’t very aware of.
When we start using CSS people talk lots about cascading and inheritance (often interchangeably). CSS inheritance is, briefly, that child elements inherit the styles that are applied to their parent elements. Cascading describes the precedence with which the style rules are applied. What seems to be common knowledge about CSS cascading is that style rules declared later take precedence over earlier rules. Understanding this was enough to let me create stylesheets for simple to medium sites, especially if I did not need to make significant changes to the design later on. But as the sites I’ve been working on have got larger and more complicated I kept running into problems caused by specificity; I vaguely knew that sometimes using “more accurate” selectors made the browsers apply the rule when simply declaring it later on in the stylesheet didn’t.
The specificity part of CSS’s cascading behaviour states that the rule whose selectors have the greatest value will be applied irrespective of the order in which they are declared. The value of the selector is decided by a relatively complicated (remembering that this is intended to be understood by us designers) rules which approximate to:
adding together the values contained in the rule’s selectors defines the strength of it’s specificity.
So the rule:
ul#menu li.selected a {font-weight:bold}
has a value of 113 (1+100+1+10+1) and the link will be displayed as bold even if I later declare a rule such as
#menu li.selected a {font-weight:normal}
because the later rule has a value of only 112.
Understanding this, first of al, lets me declare style rules in a more predictable way (especially useful when making changes to a site with a short deadline), but secondly, it shows that it’s best practise to use the weakest specificity you can to declare your CSS rules, so that it’s easier to make amendments and exceptions as the site progresses.
Comments closed for this article.
Comments: