Wednesday, November 28, 2007

Tidy up your CSS. Keep specificity in mind

Add to Delicious Digg this links to this post -

I had to clean up a large CSS file recently (actually made out of 5 different style sheets), for a large website. The CSS had become totally unmaintainable, and tackling the CSS from scratch was necessary.

This is a bit of a daunting task, and turned out very challenging. I ended up writing a guideline for this type of job, ensuring that I had a process available next time I have to do this again, or ask someone else to do it.

One of the most painful task was to solve conflicts. And I recently found a article summarising the issue very well:
http://www.htmldog.com/guides/cssadvanced/specificity/

- p has a specificity of 1 (1 HTML selector)
- div p has a specificity of 2 (2 HTML selectors; 1+1)
- .tree has a specificity of 10 (1 class selector)
- div p.tree has a specificity of 12 (2 HTML selectors and a class selector; 1+1+10)
- #baobab has a specificity of 100 (1 id selector)
- body #content .alternative p has a specificity of 112 (HTML selector, id selector, class selector, HTML selector; 1+100+10+1)

If you keep these rules in mind when you create your CSS file, you'll be able to structure it well, limiting the risk of conflicts.

If you have to assess an existing CSS document, pay attention to all nested document, and restructure first the CSS document in order to reflect this.


Other related articles & tools :: CSS specificity
- http://www.stuffandnonsense.co.uk/
- http://www.w3.org/TR/CSS21/cascade.html: which also describes inheritance, etc ..
- http://www.rebelinblue.com/specificity.php: nice little tool indicating specifity calculation for each item of your CSS

Labels: , ,

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home