Organise your CSS

Over the years I have streamlined the way I write and structure CSS to make my workflow more efficient. Here are a few tips I have picked up along the way.

Use a global reset

Web browsers apply default styles to HTML documents, but they do so inconsistently. So that you have a level playing field when you start writing your CSS rules it is important to ‘reset’ those browser-defined styles.

Eric Myer’s venerable CSS Reset is the best known global reset snippet, and he has recently updated it for HTML5. Others options to consider are the HTML5 Doctor Reset Stylesheet and HTML5 Boilerplate.

It doesn’t matter which flavour of reset you use, just make sure you use one! A global reset saves you from having to overwrite browser-defined styles at multiple locations throughout your stylesheet, and leaves you to concentrate on defining the styles you want instead of removing the ones you don’t.

Break your CSS files into logical blocks

Stylesheets can grow very large, and the bigger they become the harder they are to navigate. One way to manage this complexity is to organise your CSS document into smaller blocks, each one dealing with a specific aspect of your application.

I use CSS comments to demarcate each block of rules in my stylesheet, making it easy to scan the document for section headings rather than hunting for individual selectors:

/* Navigation
**************************************************/
			
nav { ... }

/* Footer
**************************************************/
			
footer { ... }

The document outline you settle on will be a matter of taste, but I typically divide my stylesheet into the following sections:

  • Global reset
  • Minimal base styles (generic)
  • Extended base styles (site specific)
  • Common shared styles
  • Page structure
  • Navigation
  • Headings
  • Footer
  • Forms
  • Printer styles
  • Handheld styles

The ‘global reset’ and ‘minimal base styles’ sections stay the same from one project to the next, but everything else will change depending on the project requirements. I also assign a block to each major section of the website: the homepage, image galleries, contact page, and so forth.

Use indentation to nest CSS rules

Certain CSS properties are inherited by descendant elements, and it can be helpful to visualise the inheritance chain by indenting your CSS rules. This makes it easy to see where an element sits within the document tree and inherits its properties from.

#nav {
    float:right;
    }
    #nav li {
        float:right;
        width:100px;
        }
        #nav li a {
            color:#ccc;
            }
        #nav li span {
            color:#fff;
            }

Indentation is very common when writing HTML markup, but I find it invaluable for organising my CSS too.

Organise your declarations following the box model

When I was a starting out with CSS I didn’t employ any particular system for organising declarations within my CSS rules. I imagine this is how most web designers start off, but the lack of logical structure makes it difficult to locate a specific property within your CSS rule.

Once I started to get more organised I began sorting declarations alphabetically, so for instance a background property would come before a width property. There is a certain logic to that approach, but it means that related properties (font-family, color, and text-indent, for instance) are scattered around the rule instead of being grouped together.

More recently I’ve settled on a method of organising declarations that keeps related properties grouped together, yet standardises the order in which they appear within a rule.

My method is to organise declarations following the CSS box model, moving from the outside in. In addition I place properties that affect the element’s interaction with the rest of the document at the top of the rule, and text-level rules near the bottom.

#my-element {
    display:block;
    float:left;
    margin:10px;
    border:1 px solid #999;
    padding:2px 4px;
    width:200px;
    height:50px;
    color:#fff;
    font-size:14px;
    background:#000;
}

The precise order in which properties should appear is debatable (should float come before display, or after?), nevertheless I find that that this approach helps me construct a mental picture of the element’s box model and its interaction with other elements on the page.

Use shorthand property values

Many CSS properties support shorthand notation which allow you to define several properties in a single declaration. This minimizes bloat as well as making your CSS easier to read and edit.

For example instead of:

border-width:2px;
border-style:dotted;
border-color:#ffffff;

You could write:

border:2px dotted #fff;

Write for readability, not performance

When multiple selectors share the same rule, place each selector on its own line. This increases readability and ensures the selectors don’t get lost in a lengthy list. The same goes for CSS declarations. Instead of chaining your declarations together on a single line give them room to breath.

#nav li a,
h2 a,
.home aside h3 {
    margin:1em 0;
    padding:0 0 0 50px;
    color:#ccc;
}

This is much more readable than:

#nav li a,h2 a,.home aside h3{margin:1em 0;padding:0 0 0 50px;color:#ccc;}

If you want the benefits of readable CSS and the bandwidth savings of single-line notation, then all you need to do is minify your CSS immediately prior to deploying your project or on the server.

Use comments for storing notes

I usually keep comments within my CSS files to a minimum, but one place where I like to be expansive is at the top of the document, where I store ‘meta information’ about the stylesheet.

In this header comment I include the project name, the purpose of the stylesheet and author contact details.

/* F6 DESIGN
   Master Styles
   Author: Jonathan Nicol (jonathan@f6design.com)
   
   Resources
   HTML5 Boilerplate: html5boilerplate.com
   
   Colors
   Text gray: #76797b
   Link blue: #03add1
   Heading black: #1b1d1e
**************************************************/

In the example above I have also made a note of any CSS techniques I may want to refer back to later, and stored references to commonly used hex color codes. It is a pain in the butt to scour the entire document looking for a specific hex value, and I find it more efficient to store my color codes in one place. You could use the same technique to store other commonly referenced CSS values, and needn’t restrict yourself only to colors.

Share your own tips

Organising CSS is very much a matter of personal preference, and there is no right or wrong approach. If you have any of your own CSS efficiency tips to share, please leave a comment below.

21 thoughts on “Organise your CSS

  1. Jaitra says:

    Do you hear the thunderous applause? It’s the sound this front-end developer’s complete approval of all your tips, many of which are in his own stylesheet arsenal.

    I also like to order my declarations in a similar fashion, but I’m glad to now have a methodology to explain it rather than OCD—box-model stuff first, presentation following.

  2. Jonathan says:

    @Jaitra – Oh, it’s definitely OCD ;)

    Whenever editing an old stylesheet I catch myself tut-tutting when I see a padding property appearing before a margin property (shock, horror), and I invariably succumb to the urge to swap their order.

  3. Jaitra says:

    I think our “dis-order”must appear on the same page of the DSM. I snort with derision when I see people failing to place a semi-colon after the last declaration—even though not strictly mandatory—and it gets my goat if my CSS isn’t at all times perfectly indented and tabbed.

  4. reimar says:

    I am really happy I don’t care about the order of declarations any more : ) Well … not really. I just select the whole block and let TextMate order the rows by alphabet.
    Surprisingly, it doesn’t look that bad. Two nice side effects: 1) declarations with vendor-prefixes (e.g. -moz-*) or mixins (+foo) are nicely grouped 2) You will quickly identify duplicates (e.g. padding: 5px followed by padding: 10px) which helps preventing
    layout quirks.

  5. Jonathan says:

    @reimar I’m not a fan of alphabetising my declarations, but I like the idea of having my text editor automatically sort my CSS! Unfortunately textmate is out of the question because I currently work on PC. I wonder which other editors have an automatic sorting feature…

  6. Lee says:

    While most of these techniques I already employ I find the ordering of rules a little overkill, and to some extent the tabbing – although I can see it’s benefits to readibility.

  7. Good work. also Add helper classes at the end

  8. Blude says:

    Nice tips. I also like to separate my CSS in four files: layout.css, typography.css, color.css and ie.css. They’re self-explanatory and spliting the code this way helps making the files more concise.

  9. I’m using LESS (http://lesscss.org/) for optimization of my CSS +

    Also I’m having my HTML5 elements named correctly which makes CSS section commenting unneeded… e.g.

    header {
    img.logo {
    border: 0px;
    }

    }

    footer {
    p.copyright {
    font-weight:bold;
    }

    }

  10. Francisc says:

    Thanks, very nice article.

  11. Dave says:

    Excellent stuff! I particularly like the idea of adding the basic colour scheme hex values in the header!

  12. Matt Ritter says:

    Nice article. I agree, organization is important! But, the only time it’s ever been important in my projects is when I am going back and tweaking certain declarations. However, I just use the search function in Coda for that.

    But, having a nice, clean, & organized stylesheet so another developer can easily modify it later should be a common courtesy, shouldn’t it?

  13. Danilo Ramos says:

    Wow ! it’s so useful !

  14. Jonathan says:

    @Blude I’ve never been a fan of having separate stylesheets for typography, layout, etc, since as much as possible I prefer to keep the rules and declarations that apply to an element in the same place. I know lots of people use your method though.

    @Ivan Drinchev I’ve been meaning to try out the LESS framework for a while, I’ll have to give it a whirl on my next project.

  15. Jonathan says:

    @Dave I recently saw a stylesheet where the developer was storing references to all their column and gutter measurements in the header comment, which I thought was a good idea.

  16. Adam Gray says:

    Totally in agreement with Ivan… except I use sass and compass (compass-style.org)! Then each section can be in a separate file, commented as much as you like, with variables for colours and gutter measurements etc, mixins for common blocks of code (like specifying css3 attributes for -moz, -o and -webkit in one hit) and nested selectors like

    .main
        padding: 0px
        .sub-section
            background: #fff
            a
                color: #ccc

    disclaimer: I am not affiliated with sass or compass in any way!! I will just never go back to writing straight css ever again..

  17. Tom says:

    I was recently reviewing the CSS code used in some of the new sites at ThemeForest and didn’t understand the reset.css but now I do! Also, I never thought about indentation of my CSS code, just my HTML so that is also a very good suggestion!

  18. jOan says:

    Personalmente no me gusta escribir css en forma descendente pues se deja mucho espacio vacio que generan mayor peso a la hoja de estilos.

  19. I definitely have to work on my CSS organization. Thanks so much for the great tips! Favorited :-)

  20. Mariely says:

    Great tips! I’m glad to know that I have followed these guidelines.

  21. I was thinking of writing an article on the same, and you beat me to it. Great stuff!

Comments are closed.