Showing posts with label css precedence.. Show all posts
Showing posts with label css precedence.. Show all posts

Friday, January 19, 2007

Specificity (And why css does what it does)

So my friends and I at my work (http://www.freewebs.com) were trying to figure out the browsers algorithm for determining which css rules take precedence.

Here's an example. The following produces a blue h2

<style>
div h2 {
color: red;
}
#myH2 {
color: blue;
}
</style>

<div id="myDiv">
<h2 id="myH2">My Heading</h2>
</div>

So we concluded that obviously id's take precedence over tags.

However, in this situation we end up with a red h2

<style>
#myDiv h2 {
color: red;
}
#myH2 {
color: blue;
}
</style>

<div id="myDiv">
<h2 id="myH2">My Heading</h2>
</div>

It turns out after a bit of searching that the algorithm is pretty simple. Here's what the w3c had to say:


A selector's specificity is calculated as follows:

  • count the number of ID attributes in the selector (= a)
  • count the number of other attributes and pseudo-classes in the selector (= b)
  • count the number of element names in the selector (= c)
  • ignore pseudo-elements.

Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.