Five ways to improve your CSS
Over the past couple of weeks I have been reading more on the topic of CSS Specificity. As a result, I have been going over old CSS Style sheets making the code more specific.
I have listed below five methods I used to improve my CSS.
1. Comments are a man’s best friend
Adding comments above each section of CSS keeps the formatting very clear and intuitive for myself and anyone else looking to search my style sheet. I also find it a good idea to write inline comments if I often use a specific fix at the time of writing the selector. This is useful as often you may return to view a style sheet and wonder why you wrote the rule the way you did.
2. Be specific
Previously I have often relied too much on the !important rule. Recently I started to read and understand CSS Specificity (see article CSS Specificity). Every selector has a value associated with it and the selector with the highest value will be rendered by the browser. Being specific with your selectors prevents the reliance of the !important rule and keeps your CSS looking tidy and consistent.
3. Section your CSS
When writing my CSS I always try to keep the structure in the same format as my HTML. This allows me to have an idea of where to look for a particular class or id. For example I know any elements relating to the footer are always going to be at the end of my CSS style sheet.
4. Reset
Using a reset style sheet is vital to any project, especially when developing for mobile devices. A reset style sheet does exactly what you’d expect; it resets all selectors to zero or the browser default allowing you to start from an even baseline. Below is a link to the YUI reset I originally used:
http://developer.yahoo.com/yui/reset/
I now recommend using HTML5 Boilerplate and their reset.css
5. Be consistent
I have often wondered what’s the best way to layout my CSS. When I first started developing I would write each rule vertically, this is probably the traditional way to do so.
Lately, with the increasing CSS3 selectors I have changed this layout to a horizontal layout. I find this easier to read and it also reduces the length of the CSS. I do not recommend a specific layout as I believe everyone prefers to write their own way, however be consistent with the method you choose so if you decide to go vertical, stick to vertical. If you deciode to go horizontal, stick to horizontal