Blog

CSS Formatting

June 04, 2011 at 5:56 PM

 

Multi-line vs Single-line

Having worked with several different front-end developers, I've seen it all! Sloppy ill thought illogical code, and clean, neat perfectly executed code. One thing that gets under my skin though every time, is something that's actually quite common: Multi-line CSS.

Example:

#wrapper { 
     background: #fff;
     color: #444;
     text-shadow: 1px 1px 0 #ccc;
     padding: 40px 0;
     margin: 0 auto;
     width: 960px;
}

On its own, it's beautiful. I understand that the #wrapper has a certain list of wonderful properties that are easily readable. However, the confusion comes when I do this for a large website. Scrolling through thousands of lines of code looking for the #wrapper, or even hundreds of lines of CSS, and all the selectors and properties just become a big mess.

So - what do I do? Single line. Yup. Seems a little ugly at first, but when you build a website it just makes sense. It makes even more sense after I've built the website and and looking for a particular selector. When scanning, we naturally want to scan down, then read across. When searching for a selector, I don't want my scope to be cluttered with background-position.

#wrapper { background: #fff; color: #444; text-shadow: 1px 1px 0 #ccc; padding: 40px 0; }

But I even like to go further than this. I prefer that my CSS code matches up with my HTML. Adding indention to contained elements helps me recognize obvious hierarchy and helps me relate the css to the HTML it's modifying.

cssHeirarchy.jpg

Some may argue, that with this approach, it's not quite as easy to find the properties you're looking for. However, usually, there's only like 5 properties attached to an element. I'd much rather be able to easily scan and find the 1 selector out of hundreds that I'm looking for, rather than worry "which of these three properties am I wanting to find".

What are your thoughts?





Tags: html css coding
Category: CSS

Comments are Closed

Posted by Aaron on
I usually know the line number i'm looking for thanks to Firebug. So this is not really ever an issue for me. I much prefer multiline with comments indicating sections. For example:

/*---
| Post Formatting
---*/

.post {
}

.post .title {
}

/*---
| Search Results
---*/

.search {
}


etc
Posted by michael on
Hey Aaron,

I also would typically know the line number as well via firebug, but there's a lot of time that you're editing your CSS document without firebugging, and having a structured CSS document that demonstrates hierarchy becomes important. You wouldn't write your HTML non-indented, why not your CSS?

In the end you usually have only a few CSS Properties. But hundreds of CSS selectors. I'd much rather have more easily scan-able CSS than properties.