As one who works with front-end code on a daily basis, it can quickly become an annoyance when perusing through code someone has written, if there’s no attention to detail. Specifically when dealing with the format of that code. While this applies to more than just CSS, I’ve decided to simply focus on it alone in this article. Why? Well, because I was just reading a tutorial from an unnamed website which I subscribe to, and I stopped reading it because the CSS was all over the place.
Now the following rules are obviously nothing more than a personal preference of mine, but I think they’re hard to argue. Let’s get to it.
Declaration Blocks
First and foremost, declaration blocks should blocks, not a single line. Sure, developers have larger screens and we read left to right, but CSS each declaration deserves it’s own line and should be indented. Each declaration is far easier to read this way.
Good
#foo {
font-weight: bold;
margin-left: 10px;
}
Bad
#foo {font-weight: bold; margin-left: 10px;}
NOTE: If you were to have only a single declaration, I’m personally okay with making it a single line. I don’t do it, because if I have to add a new property/value it’s easier and it keeps everything more consistent.
Space Between Property and Value
This is one of my biggest pet peeves. I’m not quite sure why, but I just really don’t like it when a space isn’t used between the property’s colon and the corresponding value.
Good
#foo {
font-weight: bold;
margin-left: 10px;
}
Bad
#foo {
font-weight:bold;
margin-left:10px;
}
Order of CSS Properties
Methods of organizing your CSS properties vary. Some prefer to do typography properties first, some prefer listing position and float values first. But why not just alphabetize them? Makes it much easier to scan and others don’t have to figure out what scheme you’re using.
Good
#foo {
border: #CCC solid 1px;
font-size: 12px;
font-weight: bold;
margin-left: 10px;
width: 400px;
}
Bad
#foo {
width: 400px;
border: #CCC solid 1px;
margin-left: 10px;
font-weight: bold;
font-size: 12px;
}
NOTE: If you haven’t realized this by now, Firebug and Safari/Chrome inspector’s also organize CSS properties this way too. Making it easy if you edit your values there and want to copy and paste them into your styles sheet.
Many more…
A book could be filled with ‘best practices’ on this stuff, but some of the simple things are ‘read and heed’. Make your code readable and you will be rewarded when it comes time to update it. And for those who are looking to save every byte they can, go ahead and compress/minify your production CSS file(s).
If you have something that just totally gets to you, post it in the comments below. I like seeing techniques others have in mind as well.
