Useful tips for writing efficient CSS
Jonathan Snook has posted a few great CSS coding tips in Top CSS Tips. Several of them come down to personal preferences, and it seems my preferences differ a bit from Jonathan’s in some cases, so I thought I’d go through his tips and note my take on each of them.
px for font sizes
Jonathan’s arguments for using
px make sense, but I always use
em. I’ve learned how to use a combination of percentages and ems and feel comfortable sizing text that way.
CSS declarations on one line
Unlike Jonathan I use a single line for rules that only contain one declaration, but multiple lines for rules with multiple declarations. TextMate’s code folding takes care of the rest for me. Jonathan makes a valid comment about file size savings with single line declarations though.
Blocking the Styles
I do pretty much the same thing: first element declarations, next global classes, and finally the layout containers and sections.
Jonathan suggests supporting only the latest browsers. I agree, but can’t always go all the way. However unless specifically requested by the client, IE/Mac gets no CSS and IE/Win 5.* will suffer the consequences of their faulty CSS box model (which I try to avoid anyway). I do like to keep the few hacks that are needed for IE/Win in a separate file, loaded with conditional comments.
overflow:hidden while I almost always use the method described in How To Clear Floats Without Structural Markup at Position Is Everything.
Yes, realising that IE doesn’t handle overflow correctly will make it easier to understand what is going on when floats start dropping.
Allow Block Elements to Fill Their Space Naturally
Very good tip. Not specifying both width and margin, padding, or borders for an element will avoid most problems with the CSS box model in IE 5.*.
Use CSS Shorthand
I am a bit of a shorthand fanatic, so I agree. I even wrote an article on CSS shorthand: Efficient CSS with shorthand properties.
Avoid Unnecessary Selectors
Another great tip. I make an effort to keep my selectors as minimal as possible. I have seen stylesheets where selector verbosity has gone completely out of control, resulting in huge filesize overhead.
Keep it Simple
One of my main guidelines, so I agree fully.