SEOClerks

Using specificity in your stylesheets



Enter a reason for deleting this comment

Using specificity in your stylesheets

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 forms on your site to be 30em wide but your search form needs to be only 15em wide:


form {width: 30em;}
form#search {width: 15em;}

Whenever you want to create a new form you do not have to worry about changing anything in the CSS, as you know it will be styled correctly. However, on larger sites you will find more and more exceptions will start to creep in. Maybe you will have a login form that you want to be 20em wide or a larger application form that needs to be 40em wide. 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.

Comments

Please login or sign up to leave a comment

Join
anwebservices

Nice post. Thanks for sharing Using specificity in your stylesheets Hope you will contribute more posts like this to our community Using specificity in your stylesheets




Are you sure you want to delete this post?