Main Contents

How Websites Work: CSS Specificity

How Websites Work

While I’ve only briefly touched on the role of CSS in a website, I thought I’d quickly cover CSS Specificity.

CSS selectors are used to target a set of of objects in the DOM of a website (that set may only contain one object). For example if one wanted to select all of the links within paragraphs they might use the following selector:

p a{ ... }

Or if they wanted to target all links with a class of “internal-link” that were within an element with an id of “sidebar” they might use this:

#sidebar a.internal-link{ ... }

CSS selectors become particularly powerful when you begin mixing in id’s and classes as in the second example.  In a more complex website that may have several thousands lines of CSS, the specificity of a CSS rule can be very important.

Here is how parts of a selector are assigned weight

  • HTML Elements (div, p, a, ul, etc) = 1
  • Class Definitions (’.internal-link’) = 10
  • id (’#sidebar’) = 100

Take a look at the first selector we used about (p a{ … }). This selector uses two html elements and since we know HTML elements have a specificity of 1 we can add those together and we see the specificity of this selector is 2.

For the second selector we have an id (’#sidebar’), an HTML Element (’a') and a class definition (’.internal-link’). When we add these up they have a specificity of 111.  Note that an HTML Element with a class definition counts for 11, similarly an Element with an id would count for 101 (’div#body’ for example).

Higher specificity gets priority and this is well supported in all browsers.

Enjoy!

MT @ June 25, 2008

Leave a comment


Feed