Pages

Labels

Powered by Blogger.
Sunday, September 2, 2012

Using specificity in your style sheets


Specificity is very useful when writing CSS, as it allows you to set general styles for common elements and then override them for more specific elements. For instance, say you want most of the text on your site black, except for your  intro text, which you want gray. You could do something like this:

p {color: black;}
p.intro  {color: grey;}

This is fine for smaller sites. However, on larger sites you will find more and more exceptions will start to creep in. Maybe you want to have the introductory text on your news stories blue and the introductory text on your home page on a gray background. Each time you create a more specific style, you will probably need to override some of the general rules. This can lead to quite a bit of extra code. It can also start to get very complicated, as one element may be picking up styles from a variety of places.

To avoid too much confusion, I try to make sure my general styles are very general while my specific styles are as specific as possible and never need to be overridden. If I find that I have to override general styles several times, it’s simpler to remove the declaration that needs to be overridden from the more general rules and apply it explicitly to each element that needs it.

0 Comments: