How Should You Format Your CSS?

Does it matter how you format and organize your css? Are there compelling reasons to writing single line css as opposed to multi-line css? Or in the end is it all a matter of personal choice?

Last week while putting together my post on SMACSS guidelines, I noticed that in the appendix, Jonathan had some thoughts about css formatting. I thought it was a conversation worthy of a post and also fit with the recent talk here about different ways to write css.

Instructions for exam format

Why CSS Formatting is Important

If the only reader of our css was a browser, then how the code was formatted wouldn’t matter. We’d all minify our css and be done with it. You and I might not be able to read the minified code, but browsers would be fine with it. In fact we probably should be minifying our production code at this point.

However, we do need to read our css and likely have others read it as well. Given that human beings will be reading your css the basic goals of formatting should be.

While we should write code that we can both read and maintain first and foremost, we can’t ignore that other people will likely read our code at some point. We should also think of our future selves. I’m sure you’ve written css that seemed clear when you wrote, but not so much several months later when you needed to modify it. I know I have.

CSS with multi-line formatting

Different Styles of CSS Formatting

There are a variety of ways to format css, each with some pros and cons. Ultimately I don’t think there’s a single way css needs to be formatted as we all have different preferences. Still we should be aware of the pros and cons of the choices we make.

One of the first formatting choices you’ll make is to write single line or multi-line css.

Single line css — makes it easier to find selectors across a document, however it’s usually harder to find a specific property within a selector. This wasn’t so much an issue in the past when we didn’t use too many properties, but as css has given us more to play with and vendor prefixes have entered the picture, our list of properties has grown.

1
2
3
4
5
#globalnav { }
#globalnav a { }
#globalnav a:hover { }
#globalnav li ul { }
#globalnav li ul a { }

Having all your selectors grouped together like above, each on a single line makes it easy to scan a file and find blocks of code that style a particular design element, in this case a global navigation bar. It would be quick to zero in on #globalnav a for example, even in a large document.

However once you start adding in some properties it’s not so clean and nice.

1
#globalnav {list-style: none; font-family: 'Helvetica'; border-radius: 7px; background: #777; overflow: hidden; -webkit-box-shadow: 2px 2px 10px #ccc; box-shadow: 2px 2px 10px #ccc; -moz-box-shadow: 2px 2px 10px #ccc; -o-box-shadow: 2px 2px 10px #ccc; padding: 0; background-image: -webkit-linear-gradient(#777, #555); background-image: -moz-linear-gradient(#777, #555); background-image: -o-linear-gradient(#777, #555); }

That’s one long line of css. Not too hard to find the #globalnav selector, but not too easy to find specific properties within.

Multiple line css — is the opposite. It’s easier to find properties within a selector, since each get’s it’s own line, however it’s usually harder to find a specific selector as more scrolling up and down is needed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#globalnav {
  list-style: none;
  font-family: 'Helvetica';
  border-radius: 7px;
  background: #777;
  overflow: hidden;
  box-shadow: 2px 2px 10px #ccc;
  -webkit-box-shadow: 2px 2px 10px #ccc;
  -moz-box-shadow: 2px 2px 10px #ccc;
  -o-box-shadow: 2px 2px 10px #ccc;
  padding: 0;
  background-image: -webkit-linear-gradient(#777, #555);
  background-image: -moz-linear-gradient(#777, #555);
  background-image: -o-linear-gradient(#777, #555);
}

Much easier to read the properties of #globalnav when written on multiple lines, isn’t it? Of course the other selectors around it have probably been pushed off the screen and so finding #globalnav a might not be as quick and easy.

Drawing of a school of fish organized into a single larger fish

Organizing and Improving CSS Formatting

You probably have a strong preference for one of the two styles of formatting above. In either case there are things you can do to improve readability and maintainability.

Ordering css properties — With either single or multiple lines we can be consistent with the order we write properties. Jonathon Snook suggested an order of:

Seems like a good idea even if you prefer a different order of property groups. In the multi-line case we could leave a blank line between groups and in the single line case we might compromise and start each group on a new line.

Tabs between properties — With single line css some people have attempted to use whitespace through tabs to improve readability.

Unfortunately properties don’t necessarily line up in columns well since they aren’t the same from one selector to the next. I’ve tried this a few times and outside of special cases have never found it to work well.

Indentation of nested selectors — WIth multi-line css some will use indentation to show selector relationships and structure. The selectors aren’t technically nested, but use whitespace to make them appear that way.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#globalnav {
  property: value;
  property: value;
}

  #globalnav a {
    property: value;  
    property: value;  
  }

    #globalnav a:hover {
      property: value;  
      property: value;  
    }

While showing the relationships is appealing, I haven’t had much luck with this style of formatting either as I find the “nested” selectors get lost and appear to be properties of the main selector at first glance. It might just be case of needing to get used to it, though.

Higher Level Improvements

There are some things we can do at a higher level to improve css readability and maintainability regardless of your choices with anything above.

Sectioning and organizing files — At the very least we should be organizing our css files in some way. All your global navigation styles in one section and your footer styles in another. Perhaps you’d prefer all typographic styles in one location and all color styles in another.

It’s not always clear how best to organize sections though, which is what led me into this recent look at css.

Taking things a little further you might choose to use a single css file or multiple css files. Multiple files might be cleaner, but require additional http requests.

Comments — You certainly want to use comments for for major sections and probably for specific properties to remind yourself why you chose a particular value. If you still use the occasional hack for one browser or another a comment is likely necessary.

Comments need to strike a balance. Commenting everything is just as bad as commenting nothing,

Better naming of classes and ids — This is always a good idea. Good names need little explanation, though it’s not always obvious how to best name classes and ids.

Abstract art with the word Formatting

My CSS Formatting Practice

You might be curious about my formatting practices. I’m ashamed to admit they haven’t changed much over the years. I still format based on habits established long ago.

Early on I made the decision to write single line css for a couple of reasons.

  • Less whitespace to keep file sizes smaller. This is in the days before minification.
  • Ease of finding selectors. I used less properties in the past

Since then I’ve experimented here and there with refining things, but nothing has stuck. When presenting examples here I do write multi-line css, since I agree it’s much easier to read for short blocks of css.

I’d like to tell you I’ve been good at commenting my code, but I can only say I’ve been good on an inconsistent level. I generally keep files organized, but the comments don’t always find their way in. I’m happy to say I’m getting better at being more consistent.

I’ve typically organized css styles in a top down approach to mimic how the html is structured, as I suspect most of you do. There are sections for base styles and common classes, but otherwise my css is typically organized as follows:

1
2
3
4
5
6
7
8
9
10
11
#header { }
blocks of styles relating to the header

#main-content { }
blocks of styles relating to the main content

#sidebar { }
blocks of styles relating to the sidebar

#footer { }
blocks of styles relating to the footer

I’m been consistent in regards to naming classes and ids, though I’ve changed my convention over the years.

CSS

Closing Thoughts

I think how you format your css is mostly a matter of personal choice. If you’re working in a team it makes sense to agree upon a consistent system, but when working for yourself it’s hard to argue against writing it your own way. You aren’t going to know the preferences of those who later read your code so why try to predict it.

Your main choice will be single or multiple lines. After that you should try to refine your approach to make things more readable and maintainable. You can organize files and properties, try tabbed or nested indentation, or anything else you think will make your css clearer.

I have a feeling my current preference is going to change once I explore css preprocessors. I think it’ll be enough of a difference to shake me out of long ingrained habits. I assume at that point I’ll write multi-line and nested preprocessed css and output minified css for production.

However, viewing source code was and is a great way to learn to code and I want to provide that resource here. Whether that means not minifying or whether it means providing a non-minified version for download is something I’ll decide when I get there.

How about you. Do you have a formatting preference? Do you write single line or multi-line css? What additional refinements do you make to improve readability and maintenance?

Download a free sample from my book, Design Fundamentals.

26 comments

  1. That’s why I think using LESS (or SASS) could be much more easier for newbies and pros to code better style sheets: nesting and mixing selectors. So far the drafts for CSS4 sadly don’t show any of them.

    • I think the issue with newbies is that all the abstractions (variables, mixing, etc) could seem a bit daunting and perhaps keep some away from trying to learn. I can understand that, though as long as those things aren’t necessary I don’t see why the learning curve would have to be any steeper.

  2. Single line for me. It drives me absolutely nuts the volume amount of scrolling required for the multi-line approach. I know I could use line number search, but that’s just a different process for the same thing. I would much rather find what I’m looking for with a few scrolls, then scan the single line for what I need. Turning on line wrap also negates the left to right scrolling issue from your example for the most part. I usually have code that is well identified as far as commenting, so the blocks are easy to scan. My style sheet is typically about 200 lines instead of the massive 1000 line monsters.

    • James, that’s how I’ve always felt too. I’ve been more concerned finding selectors in the document than properties within the selector. With single line you can quickly zero in on the selector you want and then scan across the line to find the property.

      I am rethinking that approach though as the property list has grown longer and they’re getting harder to find. After writing this post I started wondering if a hybrid approach could be a nice compromise. Maybe start new groups of properties like the ones Jonathan mentioned on new lines, but have properties within those groups remain on a single line.

      @Ryan – In my case I only use a few browser specific properties in practice. Some, but not a lot. Even though I tend to write single line css, I will use multiple lines here and there with vendor prefixes being one place where you’ll see more than one line.

  3. Another drawback for single line CSS is that diff between files is too hard. It’s almost a nightmare to review single line CSS on github.

  4. I just deal with it. With the browser prefixes it can be a little crazy, but on the other hand there are techniques you can use to cut down on them. Say if you use the same box-shadow declaration on 10 different elements in a page it’s easy to gang those classes up into one declaration, then leave the other specific declarations to another line.

    As I mentioned with wordwrap, it makes your lines show up on one screen. So even if all the declarations are super long, it’ll just show up as a 3 or 4 line rule.

    • Sounds like we deal with it similarly. The only difference is I’ll manually break the single line at times instead of letting wordwrap handle it. I might break the vendor prefixes so they all fall on a single line or each gets its own line.

  5. I find the biggest problem with LESS and SASS is that it requires whole team buy-in to use. I work in a department of 7 web designers, then there is a much larger array of developers. We repurpose code all the time, so to go with that approach becomes problematic if you’re the only person going about it that way.

    • Yeah, I’ve seen that as an argument against using them. Obviously if you’re working on a team then there needs to be consistency. Everyone needs to be on board or you can’t use the preprocessor.

      I’m a lone coder so I don’t have that same issue. My concern is more clients updating things after I’ve built the site. Not all of my clients will do that, but some will. Once they do the Sass and Less stuff is out the window.

      What I’m thinking is I’ll start using Sass for myself only. I’ll use it for projects where I can be reasonably sure I’ll be the only one touching the code. I’ll see how it goes and then decide from there whether or not to use it for client sites. I do find the abstraction layer preprocessors add very appealing.

      • As far as using CSS preprocessors, ideally, your whole team would get on board and use the same CSS preprocessors, though you can still use LESS or SASS for your initial build, even if no one else on your team does.

        I use LESS on the initial build, as I am the only one touching the CSS at that point. Once that’s all done, I upload the outputted CSS and use that for the rest of the project.

        • I’d think that loses some of the maintainability benefit, though I assume there’s still benefit in using the preprocessor only for the initial build.

          I’m guessing you wish everyone else was also using LESS, but even if they aren’t you’re glad to be using it yourself.

  6. I structure my CSS similar to the SMACSS method, though I only prefer to use BASE, LAYOUT, and MODULE sections in my stylesheet.
    I’ve found for STATES, I can add those after the specific modules that have different states and just keep those in the MODULE section, and for the THEME section, I like the concept, though have not found that I’ve needed it yet.

    I set up a table of contents at the top of my stylesheet that looks something like this.

    * BASE – @Font-Face Fonts, Resets, Base Styles
    * LAYOUT – Major Components: #header, #primary-nav, #body, #footer
    * MODULE – Minor Components: .logo, .main-col, .side-col

    Then, if I have different media queries, I repeat this organization structure in those too.

    This is a new practice I adopted after reading through SMACSS so I don’t have any sites to share as an example yet.

    I have also been considering using classes solely instead of classes and ids for CSS styling. This article got me thinking in that direction. http://oli.jp/2011/ids/

    As far as writing the CSS, I prefer multi-line if the rule has more than 2 or 3 properties. I also try to order my properties alphabetically. This is a company practice that helps everyone know where properties should be.

    Lastly, I’ve started implementing some concepts from Jeremy Clarke’s DRY CSS presentation.

    http://www.slideshare.net/jeremyclarke/dry-css-a-dontrepeatyourself-methodology-for-creating-efficient-unified-and-scalable-stylesheets

    I would recommend checking that out. Would like to hear your thoughts on that concept.

    • Thanks Brett. I appreciate you sharing your practice. The more I’ve been looking into all this, the more I’m leaning toward a similar Base, Layout, Module approach. Whether or not I need more is something I’ll let grow organically.

      I was thinking the same thing about repeating in media queries too.

      Maybe it’s just habit, but I’m thinking I would hold onto IDs for certain things. We’ll see what happens. I’m still taking everything in and can’t say I’ve really put much of this into practice. A tiny bit, but not a lot yet.

      Thanks for the link to Jeremy Clarke’s presentation. I have the slides and the video itself bookmarked. It’ll probably be the weekend before I get to watch, but I will. I found another video/slide presentation about all this css stuff this past weekend that I’ll mention in a post next Monday.

  7. One way to piss off other developers you work with would be to use single line CSS. Efficient and speedy debugging of single line CSS is incredibly difficult and as Nikos says it makes diffing a file pretty much impossible. It’s a massive no-no.

    There’s nothing wrong with scrolling in a CSS file. Do a search for the selector if you don’t know exactly where it is in the file, or break your code down into separate files and use @imports if the file is too big.

    Minifying a file for production sites will merge all @imports into one file and gets rid of whitespace for optimal file size and a decrease in HTTP requests.

    There’s simply no excuse for using single line CSS.

    • Funny Daan. I certainly don’t want to piss off other developers. :)

      I’ve always worked alone and writing code that others work on naturally hasn’t been a huge consideration given that there’s no team. Of course I should still expect others will go through my code at some point.

      Early on I found single line much easier to read. It’s easier for me to scan through selectors to get a good overview of how a file is set up and then later dig in to adjust properties. I agree though that scrolling really isn’t that hard and some of my preference is based on the past when larger files weren’t organized all that well. I’ve worked on some truly awful css at times.

      A lot of these recent posts have been for me to question my own practices so I can better understand the benefits of changing them.

    • Thanks David. Another link bookmarked. I scanned through and will dig deeper when I have a few moments. I caught at the end the suggestion that using these guidelines lessens the need for a preprocessor. Interesting. It wouldn’t have thought that would be the case with any kind of formatting, but I’ll see what I think when I have more time to look through the guidelines.

  8. One big pro of using Single Line style is less scrolling. That’s the main reason I use single line. As for harder to read? Hmm. I guess you simply get used to the one line.

    • That’s why I went with single line too. I found it easier to scan selectors and then once I’ve zeroed in on the group I want I could scan across for the properties.

      I can understand the issues though. Anyone who works with version control and needs to compare files would prefer multiple lines. it’s interesting hearing everyone’s opinions.

      I think some of this comes down to whether you work alone or in a team and what your overall development process is. What works under one set of conditions may not work so well under another.

  9. I switched from single to multi-line about 2 years ago and never looked back.

    1. Trying to debug single-line CSS is a nightmare…how can you see diff’s / conflicts in revisions if all properties are on the same line?

    2. Vendor pre-fixes would make single-line CSS really long…ridiculously long.

    3. File-size doesn’t matter if your minify for production…so why squish everything together with single-line on the readable files?

    4. “Multi-line makes files long” isn’t an issue if you use LESS / SASS to break CSS into appropriate chunks then recompile with @import. As others have said, you have selector / line searches.

    Whilst I agree that CSS is “each to their own”, there are some approaches that just cause way more headaches when more than one person is involved.

    Use multi-line.
    Avoid ID’s in your CSS, their high specificity causes holes that are hard to dig yourself out of.
    Amongst your team, come up with a generic structure that you all like (we like SMACSS)
    Amongst your team, come to a decision on a pre-processor and all use it

    • I’m ashamed to admit I haven’t yet caught on to version control. It’s one of the topics I plan on exploring in the near future. Still reading up on it. It’s such a different process from the way I work, but I know it’s the right way to do things. So for me diffs and conflicts haven’t entered into my formatting choice, though I now see why that’s important.

      With vendor prefixes I do tend to write them on different lines. I’m not 100% single line.

      I’m still not with Sass or Less either. That’s coming soon. I decided on Sass and expect I’ll be changing some practices as I start using it.

      I’ve mentioned it in a couple of comments about the working by yourself and working in a team. I usually work alone and some of the team issues just hadn’t really occurred to me. I completely understand them now that I’ve heard everyone’s opinions.

      All your conclusions are pretty much where I’m heading. Even though I work on my own, I can see why they’re all a better approach than what I’ve been doing.

Leave a Reply

Your email address will not be published.

css.php