CoffeePowered

CSS coding standards

Well, it’s now 2010 and as usual, January brings with it many self-made promises and resolutions, one of mine is to write more, even if it’s just quick tips & tricks rather than lengthy diatribes which I always want to write, but never seem to find the time.

During the back end of last year I started to experiment with one of the more boring aspects of CSS, but one of the most rewarding in the long-term: How I actually write, organise and maintain my CSS files. These are relatively minor tweaks, but I thought I’d share them in case anyone finds them useful.

I’d just like to note that these are my personal preferences, you may disagree entirely with the way I do things and that’s fine, feel free to drop a comment below if you’d like!

Single vs. Multi-line

So lets get this out of the way, I hate single line CSS rules, they’re a pain-in-the-ass to navigate and can cause problems with some source control tools which may only tell you which line has changed and not which property has changed specifically or when running your code through the validator and getting errors which refer to specific line numbers as well as times when you might not have syntax highlighting to help you quickly visually identify properties and values (such as viewing CSS in Firebug).

I’ve never written my CSS rules as single-line and I doubt I’ll ever start.

Ordering of declarations

One of my most common bugbears is with the ordering of declarations, a lot of the CSS files I come across in my ‘day job’ are simply not ordered in any meaningful way, some have a semblance of ordering based on the personal preferences of the designer and may have width & height rules together, floats and positions together for example, this always differs from designer to designer.

The best way to order declarations is alphabetically, it makes it far easier to scan through and visually locate a specific declaration, especially in large rules. Also, for teams of multiple designers it’s far easier to add declarations to an existing rule as they simply slot in alphabetically.

1
2
3
4
5
6
7
8
9
10
ul#nav_primary li a {
    border:0;
    color:#999;
    display:block;
    float:left;
    font-size:1.2em;
    font-weight:bold;
    padding:0 10px;
    text-decoration:none;
    text-transform:uppercase; }

Curly braces

This might be one of those decisions where people think “Does that *really* matter?”, but I’ve started to place my closing brace on the same line as the last declaration. The reason behind this is to improve the visual distinction between rules which helps when scanning quickly through a large CSS document.

Previously, I’d place the closing brace on it’s own line, like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
h1 {
    border-bottom:2px solid #ccc;
    font-size:2em;
    line-height:1.5em;
    margin:0 0 18px 0;
}
h2 {
    font-size:1.333em;
    line-height:1.125em;
    margin:1.125em 0;
}
h3 {
    font-size:1.1667em;
    line-height:1.2857em;
    margin:1.2857em 0;
}

Now that the brace follows the last declaration it improves the spacing between rules, or course I could simply add another line after each rule, but that simply adds to the filesize and needlessly pads out the document. This method also places all of the selectors on their own tab level which helps when scanning through to locate a selector.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
h1 {
    border-bottom:2px solid #ccc;
    font-size:2em;
    line-height:1.5em;
    margin:0 0 18px 0; }

h2 {
    font-size:1.333em;
    line-height:1.125em;
    margin:1.125em 0; }

h3 {
    font-size:1.1667em;
    line-height:1.2857em;
    margin:1.2857em 0; }

Closing semi-colon

The closing semi-colon on the last declaration of a CSS rule is optional, while some people will no-doubt argue that dropping this will lead to smaller filesizes I’d always argue that long-term maintainability is more important, especially on larger projects with multiple developers or for projects which are handed to clients to maintain themselves.

By keeping the closing semi-colon in place anyone can quickly dive into the file and add rules without needing to worry about where the semi-colons are.

Further reading

I’ve only skimmed the surface of CSS coding standards to highlight some of the ways I like to do things, If you’re interested in making your CSS more readable, and especially more maintainable then I’d highly recommend you read the PDF version of this BarCamp presentation by Natalie Downe on “CSS Systems for writing maintainable CSS” which is a must-read and chock-full of excellent advice.

What do you do?

Do you have any personal preferences when it comes to writing your CSS? Feel free to hit the comment box below and let me know!

Tags: , , , ,

This entry was posted on Monday, January 4th, 2010 at 21:04 and is filed under CSS, p52, Tips and tricks. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

You should RSS feed icon subscribe to future posts and Twitter follow me on Twitter

29 Responses to “CSS coding standards”

  1. stef says:

    @stanton could I recommend you take a look at SASS? http://sass-lang.com/ it’s a markup language that generates well-formed css

  2. Lee Theobald says:

    Nice post Paul. Out of curiosity – how about comments. Do you tend to place a big comment at the top of the file to explain what it’s for? Include a table of contents? That kind of thing.

  3. Clive Walker says:

    Ordering declarations alphabetically seems like a good idea that I wish I had thought to do myself. The only thing I would add is to organise the style sheet into sections (main elements, images, headings etc) with easily readable comments between them (perhaps with each comment containing an easily findable character or flag).

  4. Stanton says:

    Hi Lee & Clive, thanks for the comments!

    I didn’t really go into CSS structure and comments as I felt that was worth a whole post of their own! I hope to write a bit more around those soon.

    When it comes to organising the CSS file I do separate rules into sections, usually in this order

    reset (included)
    body (html, body)
    structure (header, sections, columns, footer etc)
    typographic baseline
    layout

    and then into the styling of sections of the site. As you’ve both mentioned, each section is seperated by clear comments, I’ve not really experimented with a table of contents, but for some of the large files I work with it might be a very good idea :)

  5. Matt Bee says:

    I still write my CSS rules on one line (unless the code will be used by another developer). I also indent based on the cascade, for example:

    #header { float: left; width: 960px; /* etc */ }
    #header h1 { float: left; /* etc */ }

    I find that helps me read my stylesheets.

    Another thing I tend to do is order rules in a loose “layout, dimensions, font, color background” structure, rather than alphabetically.

    But each to their own and I have been known to randomly change my structure anyway!

  6. Matt Bee says:

    If whitespace at the start of a line wasn’t stripped, you’d see what I meant!

  7. Stanton says:

    So it’s pretty safe to say, Matt, that we’d probably hate to co-author a CSS file! :)

  8. Craig Rowe says:

    Have to agree with Clive re: the ordering alphabetically. I’d previously been one of those guys who tries to order by functional grouping (and clearly each time I did that I had a slightly different idea of how to group them and in which order they appeared!).

    Have you ever used any kind of server side pre-processing? Either to add functionality such as variables etc (Something like the various implementations of LessCss).

    Also minor point on the curly braces, you may find that authors are fighting against the default preferences of their chosen editor e.g Some editors will auto format braces onto new lines by default.

  9. Danny Barnes says:

    Enjoyed this post Stanton… I’ll be changing the position of my curly brace for sure, and I’ll try to keep things alphabetically from now on – seems like a good idea to me.

    One habit I have is to use “border: solid thin red;” on all main layout elements when first sorting the layout of the site.

  10. Always good to get an insight into other developers working-ways, personally I write single-line per selector and alphabetically order declarations.

  11. Phil says:

    Great post. I don’t necessarily agree with all the points, but it’s great to see what works for other designers. In my experience I have found incorporating single line CSS for link styles ‘hover, active, visited etc’ makes the code more readable. Thanks for sharing!

  12. Dan says:

    Great article!

    Your methods are very similar to my own, with the exception of closing curley brace, however this does look much better and I will adopt this standard too.

    As I get more and more into designing in the browser, and as such banging out CSS at mach 2, I need to stick to a coding standard that makes what I write legible.

  13. Yaili says:

    You’d hate to edit my stylesheets, Paul. Also, you’ve beat me to writing an article focusing on coding standards etc. — so I’ll post my article as a reply to this one, some time this year…

    Regarding my own code, I make everything one line. If the selectors are small enough and are almost the same, I even put two or three on the same line. If there is one thing I hate, is a CSS file that has 5,000 lines when it could easily have less than 900 — eek!

    CSS optimizers/formatters are my friends and I’m not afraid of using them on your stylesheets ;)

    I only alphabetize if I have nothing better to do or am I’m trying to procrastinate.

    I comment a lot, for me and for others. And I like to keep a tidy, consistent and logical structure to my files; add a list of colours and index at the beginning, etc.

  14. Dan says:

    As for alphabetising I can see why people would find that helpful but, sometimes frustratingly, that’s not how my brain works. I order my CSS in order of the element’s appearance in the document. Not for everyone, I know but works for me.

  15. Stanton says:

    @Craig – I’ve never really looked into server side processing, I’ve been tempted to deliver my CSS via PHP to support CSS variables although it does add another layer of abstraction which could increase the maintainability overhead for multi-person teams.

    I know what you mean about the default preferences of your editor, I used Visual Studio recently which was paticularly painful but I think most can be either configured or disabled, I don’t use auto-formatting so it’s not really an issue for me :)

  16. Stanton says:

    @Danny – Thanks! I’m glad you liked the post :) If I had a pound for every time I’d written border:1px solid red; I’d be a millionaire! (or at least a tens-of-thousandsaire)

  17. Stanton says:

    @Yaili – Sorry for pipping you to the post but you’re right, I think that’d drive me nuts :) but as you said there’s plenty of formatters which can change the layout of stylesheets to your preferences. Which ones do you use the most?

    I do sometimes put the selectors on the same line if they’re small enough, such as:

    h1, h2, h3, h4 {
    property:value; }

    The list of colours as part of the opening comments / table of contents is a good idea, I might have to borrow that one!

  18. Yaili says:

    Sorry, Paul, you can’t borrow it! ;)

    This is the only formatter that does the trick for me, actually: http://www.lonniebest.com/FormatCSS

    All the others are a bit less detailed. I’d like to find one that did all the things this one does, but that would keep the comments in though.

    When the selector is small, and has few properties, everything goes into one line. For example:

    h1 { color:red; } h2 { color:blue; } h3 { color:green; }

  19. [...] Paul Stanton gave us a look into CSS coding standards. [...]

  20. Stanton says:

    I’ll give it back, I promise!

  21. Andrew Fox says:

    I was going to just start going on about how tricky it is to share CSS files with Yaili — but she pretty much said it! As for the length of the files that are made with multi-line CSS, I don’t really think it matters if you’re using something like CSSEdit (I rarely edit a CSS file ‘raw’ anymore without some kind of tool). That said, Yaili is better than me nowadays so generally I defer to her :/

  22. Great post!

    In my opinion, closing brace on the last line just adds an extra step if you add something in later that comes after (alphabetically) everything that was already there.

    Other than that, I use all the other techniques PLUS indenting my rules so they all line up as well.

  23. That is almost exactly the coding style I have ended up with. The only difference being that I tend to omit the last semi-colon – a rather anal habit, as I’m always having to tidy up at the end.

    When I get around to implementing some kind of live css parsing thing, so I can automate development > production code form, I’ll add a rule to remove the last semicolons.

  24. Rob says:

    I generally write my CSS with more concern for readability than for speed. I indent and leave the curly braces on their own line. I should probably start to organize my declarations. Currently, I just sort them based on relationship (backgrounds together, height & width next to each other), but that isn’t hard and fast.

    For commenting, I normally sort my CSS based on cascades and the order it appears on the page. I use Comments before each area of the page (ie. /* Navigation */, /* Footer */, etc).

  25. James.S says:

    Good read, agree with much of what you say!

    Spot on with maintainability trumping file size – if that’s an issue I reckon you should run a minifier on release, leaving your dev files nice and maintainable.

    Also, from the comments, I would replace:

    border: 1px solid red;

    with:

    outline: red solid thin;

    as outline doesn’t take up space in the box model. Compensating for the temporary border on fixed width/height elements kept nagging me ’til I started using different background colors (waaay too much hassle) and finally settled on outline.

  26. Stanton says:

    Awesome tip James! Thanks for sharing :)

  27. [...] CSS Coding Standards (via coffeepowered.co.uk) [...]

  28. [...] CCS Coding Standarts [...]

otomatik kapi

kesintisiz güç kaynağı

ingilizce kursu

mermer

web tasarım