Menu Search
Jump to the content X X
SmashingConf London Avatar

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. our upcoming SmashingConf London, dedicated to all things web performance.

How To Write CSS For Others

I think a lot of us CSS authors are doing it wrong. We are selfish by nature; we get into our little bubbles, writing CSS (as amazing as it may be) with only ourselves in mind. How many times have you inherited a CSS file that’s made you say “WTF” at least a dozen times?

(Image: Toca Boca2)

HTML has a standard format and syntax that everyone understands. For years, programmers have widely agreed on standards for their respective languages. CSS doesn’t seem to be there yet: everyone has their own favorite format, their own preference between single-line and multi-line, their own ideas on organization, and so on.

Further Reading on SmashingMag: Link

A New Way of Thinking Link

Recently, I have begun to think that CSS authors could take a leaf from the programmers’ book. We need to write CSS that others can understand and use with ease. Programmers have been writing sharable code since day one, and it’s high time that CSS be written with as much organization and openness.

In writing inuit.css6 and working on a huge front-end framework at my job at, it has become more apparent to me that writing code that can be easily picked up by others is extremely important. I wouldn’t say that I’ve nailed everything yet, but I’ll share with you some things that I think are vital when writing code, specifically CSS, that will be used by others.

First, the reasoning: my number one tip for developers is to always code like you’re working in a team, even when you’re not. You may be the only developer on your project right now, but it might not stay that way:

  • Your project could be taken to another developer, agency or team. Even though this is not the best situation to find yourself in, handing over your work smoothly and professionally to others is ideal.
  • If you’re doing enough work to warrant employing someone else or expanding the team at all, then your code ceases to be yours and becomes the team’s.
  • You could leave the company, take a vacation or be off sick, at which point someone else will inherit your code, even if only temporarily.
  • Someone will inevitably poke through your source code, and if they’ve never met you, this could be the only basis on which they judge your work. First impressions count!

Comments Are King! Link

One thing I’ve learned from building a massive front-end framework at work and from producing inuit.css is that comments are vital. Comments, comments, comments. Write one line of code, then write about it. N.B. This is not meant to mean write about every line of code, as that would be overkill. Only comment where it helps/is useful.

It might seem like overkill at first, but write about everything you do. The code might look simple to you, but there’s bound to be someone out there who has no idea what it does. Write it down. I had already gotten into this habit when I realized that this was the same technique that a good friend and incredibly talented developer, Nick Payne7, told me about. That technique is called “rubber-duck debugging8”:

… an unnamed expert programmer would keep a rubber duck by his desk at all times, and debug his code by forcing himself to explain it, line by line, to the duck.

Write comments like you’re talking to a rubber duck!

Good comments take care of 99% of what you hand over and — more importantly —  take care of your documentation. Your code should be the documentation.

Comments are also an excellent way to show off. Ever wanted to tell someone how awesome a bit of your code is but never found the chance? This is that chance! Explain how clever it is, and just wait for people to read it.

Egos aside, though, comments do force you to write nicer code. I’ve found that writing extensive comments has made me a better developer. I write cleaner code, because writing comments reminds me that I’m intending for others to read the code.

Multi-Line CSS Link

This issue really divides developers: single-line versus multi-line CSS. I’ve always written multi-line CSS. I love it and despise single-line notation. But others think the opposite — and they’re no more right or wrong than I am. Taste is taste, and consistency is what matters.

Having said that, when working on a team, I firmly believe that multi-line CSS is the way to go. Multi-line ensures that each CSS declaration is accounted for. One line represents one piece of functionality (and can often be attributed to one person).

As a result, each line will show up individually on a diff between two versions. If you change, say, only one hex value in a color declaration, then that is all that needs to be flagged. A diff on a single-line document would flag an entire rule set as having been changed, even when it hasn’t.

Take the following example:


Above, we just changed a color value in a rule set, but because it was a single-line CSS file, the entire rule set appears to have changed. This is very misleading, and also not very readable or obvious. At first glance, it appears that a whole rule set has been altered. But look closely and you’ll see that only #333 has been changed to #666. We can make this distinction far more obvious by using multi-line CSS, like so:


Having said all this, I am by no means a version-control expert. I’ve only just started using GitHub for inuit.css, so I’m very new to it all. Instead, I’ll leave you with Jason Cale’s excellent article on the subject.

Furthermore, single-line CSS makes commenting harder. Either you end up with one comment per rule set (which means your comments might be less specific than had they been done per line), or you get a messy single line of comment, then code, then comment again, as shown here:


With multi-line CSS, you have a much neater comment structure:


Ordering CSS Properties Link

Likewise, the order in which people write their CSS properties is very personal.

Many people opt for alphabetized CSS, but this is counter-intuitive. I commented briefly on the subject on GitHub13; my reasoning is that ordering something by a meaningless metric makes no sense; the initial letter of a declaration has no bearing on the declaration itself. Ordering CSS alphabetically makes as much sense as ordering CDs by how bright their covers are.

A more sensible approach is to order by type and relevance. That is, group your color declarations together, your box-model declarations together, your font declarations together and so on. Moreover, order each grouping according to its relevance to the selector. If you are styling an h1, then put font-related declarations first, followed by the others. For example:

#header {
   /* Box model */
   width: 100%;
   padding: 20px 0;
   /* Color */
   color: #fff;
   background: #333;

h1 {
   /* Font */
   font-size: 2em;
   font-weight: bold;
   /* Color */
   color: #c00;
   background: #fff;
   /* Box model */
   padding: 10px;
   margin-bottom: 1em;

Please note that the comments above are not intended to go into your CSS file, but are just to illustrate my point in the article.

Ordering CSS Files Link

Ordering CSS files is always tricky, and there is no right or wrong way. A good idea, though, is to section the code into defined groups, with headings, as well as a table of contents at the top of the file. Something like this:


html {

body {


And so on.

This way, you can easily read the contents and jump straight to a particular section by performing a quick search (Command/Control + F). Prepending each heading with a dollar sign makes it unique, so that a search will yield only headings.

The “Shared” Section Link

All CSS files should have a section for sharing, where you tether selectors to a single declaration, rather than write the same declaration over and over.

So, instead of writing this…

h1 {
   font-size: 2em;
   color: #c00;

h2 {
   font-size: 1.5em;
   color: #c00;

a {
   color: #c00;
   font-weight: bold;

#tagline {
   font-style: italic;
   color: #c00;

… you would write this:

h1 {
   font-size: 2em;
h2 {
   font-size: 1.5em;
a {
   font-weight: bold;
#tagline {
   font-style: italic;

h1, h2, a, #tagline {

This way, if the brand color of #c00 ever changes, a developer would only ever need to change that value once. This is essentially using variables in CSS.

Multiple CSS Files For Sections, Or One Big File With All Sections? Link

A lot of people separate their sections into multiple files, and then use the @import rule to put them all back together in one meta file. For example:

@import url(main.css)
@import url(type.css)
@import url(images.css)
@import url(tables.css)
@import url(misc.css)
@import url(responsive.css)

This is fine, and it does keep everything in sections, but it does lead to a lot more HTTP requests than is necessary; and minimizing requests is one of the most important rules for a high-performance website.

Compare this…


… to this:


If you section and comment your CSS well enough, using a table of contents and so forth, then you avoid the need to split up your CSS files, thus keeping those requests down.

If you really want to break up your CSS into multiple style sheets, you can do that — just combine them into one at build time. This way, your developers can work across multiple files, but your users will download one concatenated file.

Learning From Programmers Link

Programmers have been doing this for ages, and doing it well. Their job is to write code that is as readable as it is functional. We front-end developers could learn a lot from how programmers deal with code.

The code of my good friend (and absolutely awesome chap) Dan Bentley16 really struck a chord with me. It’s beautiful. I don’t understand what it does most of the time, but it’s so clean and lovely to look at. So much white space, so neat and tidy, all commented and properly looked after. His PHP, Ruby, Python or whatever-he-decides-to-use-that-day always looks so nice. It made me want to write my CSS the same way.

White space is your friend. You can remove it before you go live if you like, but the gains in cleanliness and readability are worth the few extra bytes (which you could always cut back down on by Gzip’ing your files anyway).

Make the code readable and maintainable first and foremost, then worry about file size later. Happy developers are worth more than a few kilobytes in saved weight.

Code Should Take Care Of Itself Link

So far, we’ve talked about people maintaining your code, but what about actually using it?

You can do a number of things to make the life of whoever inherits your code much easier — and to make you look like a saint. I can’t think of many generic examples, but I have a few specific ones, mainly from inuit.css.

Internationalize Your Selectors Link

Inuit.css has a class named .centered, which is spelt in US English. CSS is written in US English anyway, so we’re used to this; but as an English developer, I always end up typing UK English at least once in a project. Here is the way I have accounted for this:

.centred, .centered {

Both classes do the same thing, but the next developer doesn’t have to remember to be American!

If your selectors include words that have US and UK spelling variants, include both.

Let the Code Do the Heavy Lifting Link

Also in inuit.css, I devised a method to not need class="end" for the last column in a row of grids. Most frameworks require this class, or something similar, to omit the margin-right on the last item in a list and thus prevent the grid system from breaking.

Remembering to add this class isn’t a big deal, but it’s still one more thing to remember. So, I worked out a way to remove it17.

In another major inuit.css update, I removed a .grid class that used to be required for every single grid element. This was a purely functional class that developers had to add to any <div> that they wanted to behave like a grid column. For example:

<div class="grid grid-4">

This .grid class, in conjunction with the .grid-4 class, basically says, “I want this <div> to be a grid item and to span four columns.” This isn’t a huge burden on developers, but again, it’s one more thing that could be removed to make their lives easier.

The solution was to use a regex CSS attribute selector: [class^="grid-"]{}. This says, “Select any element whose class begins with .grid-,” and it allows the developer’s mark-up to now read as follows:

<div class="grid-4">

CSS attribute selectors may be less efficient than, say, classes, but not to the point that you’d ever notice it (unless you were working on a website with massive traffic, like Google). The benefits of making the mark-up leaner and the developer’s life easier far outweigh the performance costs.

Do the hard work once and reap the benefits later. Plus, get brownie points from whoever picks up your project from you.

Be Pre-emptive, Think About Edge Cases Link

An example of being pre-emptive in inuit.css is the grid system. The grids are meant to be used in a series of sibling columns that are all contained in one parent, with a class of .grids. This is their intended use. But what if someone wants a standalone grid? That’s not their intended use, but let’s account for it should it happen18.

Note: inuit.css has changed since this was written, but the following is true as of version 2.519.

Another and perhaps better example is the 12-column grid system in inuit.css. By default, the framework uses a 16-column grid, with classes .grid-1 through .grid-16 for each size of column.

A problem arises, though, when you attempt to switch from the 16-column system to the 12-column system. The .grid-15 class, for example, doesn’t exist in a 12-column layout; and even if it did, it would be too big.

What I did here was to make .grid-13 through .grid-16 use the exact same properties as .grid-12. So, if you switch from a 16-column layout to a 12-column one, your .grid-13 through .grid-16 would’t break it — they would all just become .grid-12s.

This means that developers can switch between them, and inuit.css will take care of everything else.

Pre-empt the developer’s next problem, and solve it for them.


A few people have mentioned that some of these practices lead to a bloated CSS file. Bloat is where unnecessary code makes its way into a file, and your comments should be anything but unnecessary. It will lead to a larger CSS file, but not a bloated one.

If you are worried about increased file size then you should minify20 and gzip your stylesheets, but this is best practice (particularly for highly trafficked websites) anyway.

That’s It Link

There you have it: a few humble suggestions on how CSS authors can write code that is perfect for other developers to inherit, understand, maintain, extend and enjoy.

If you have any other tips, do please add them in the comments.


Footnotes Link

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20

↑ Back to top Tweet itShare on Facebook

Harry Roberts  is a Senior UI Developer for and type nerd from the UK. Enthusiastic, passionate and often outspoken, he is a writer, designer and member of Smashing Magazine’s Experts Panel. He tweets at @csswizardry.

  1. 1

    Great write up Harry. It’s always interesting to see how others write their CSS when there are fewer restrictions on laying it out.

    I also favour multi line, I find it so much easier to scan but again, a totally personal preference.

    Getting used to working as part of a team even when you’re on your own is great advice and something everyone should try and get into the habit of!


    • 2

      Oneline css though has the advantage of fewer lines to run through thus speeding up the initial loadtime. A mid size site with 500 lines of oneline css could easily be around somewhere like 2-3000 lines of css when using the multiline approach.

      Sure you can minify your multiline css file before uploading it to your server, but i would rather adapt (which i did recently) and skip that part.

      If you make sure to indent your css elements and their childrens you quickly get a proper overview:

      I took me some getting used to at first but after the first couple of hours it was no issue at all working with the oneline approach.

      • 3

        I agree with Martin, plus there are different ways of keeping track of changes to a CSS file, like SVN.

        • 4

          The example in the article uses version control.

          I think the author’s point about single vs multi-line css in svn is that changes are tracked per line #. So single-line css will be a bit difficult to debug based on line # alone.

          Not that I’m closed to the idea of single line css. Martin’s comment about being able to see the structure at a glance (using proper indentation) seems good enough to make me want to try single line css.

          • 5

            When coding your CSS, it’s best to use multiline, especially when collaborating – and that is the point of the article. Whenever I go live with code, be it CSS or JavaScript, I minify it anyway to strip out all comments and empty spaces.

            That said, this is a good starting point if you don’t have any sort of style guidelines set up yet, but I find many places already have style guides set up. This article is just one coder’s opinion, after all. :)

      • 6

        I also agree with you Martin I also use multi-line css before but i switch into single line css because it speeds up the initial loadtime.

      • 7

        One-line CSS doesn’t really save you many bytes. You probably still add a space after each semicolon, so that’s the same as hitting Enter. Essentially, the only extra byte is the tab character after the newline.

        Also, you can still indent multi-line CSS rules for descendants, I always do it religiously. (although in that case minification becomes quite necessary in big files).

        • 8

          Hi Lea

          When doing one-line css i’m looking to reduce the number of lines the server has to traverse in order to serve the css file, not so much reducing the number of kilobytes. Are you saying that the whitespace after the semicolon gets treated like a new line (pressing enter)? I did not know that.

          In my experience that has left me with a more swift initial load of the css file and with time i kinda like the one-line structure more as i don’t have to scroll that much.

          Wether or not one uses the one-line css, indenting is always a nice way to ensure a quick overview of the structure of the file.

      • 9

        At work we use a custom minimse/gzip css on the server when it’s pulled down anyway so comments are typically removed along with whitespace and minification takes place so what’s output to the browser is less than both multi or single line anyway.

        With that in mind, I’d prefer a local production version I can easily read and for me that’s always been multi-line.

        I do totally appreciate it’s a personal thing though as to what’s easier for people to read and that at this time, there’s no right or wrong but to me the argument is largely void by the fact that you should ideally be minifying and gzipping on live sites anyway.


        • 10

          Hi James

          We operate with gzipping and other stuff too and you’re right that it’s a personal thing when you make sure to minify and gzip.

          If you don’t do this i have had better loadtimes with one-line css files on alot of sites. Not much, but every millisecond counts and down the road i’ve found that i can more easily scan one-line css files (as long as they are indented properly) after some getting used too.

      • 11

        CSS gets read more than it does written, so for me it’s important that its readable over speed improvement, plus that’s what minify is for.

        Multiline works as you would read any other document, it’s great for scanning. With single line you’re having to pan and scan (somtime even vertical scroll :( )

      • 12

        Wait, what? Shouldn’t CSS and javascripts always be combined and minified dynamically? Thus you as much space and comments as you like, and it’s all taken care of without your extra time. Of course caching as well.

        Minifyjs, or other libraries can do it in a snap. There’s a plugin for just about every framework out there for plug and play, or more like upload and activate.

        Anyway, given that it’s done dynamically, I’d agree with extra comments as space. Saves time, headaches, and performance is just as good.

  2. 13

    Yep great article Harry. Well done.. Organising your CSS is an important part of differentiating yourself as a great front-end developer instead of just a good front-end developer


  3. 14

    Nassimbwa Catherine

    August 26, 2011 3:17 am

    very enlighting…. it has cleared some areas that were kinda puzzling me… nice read

  4. 15

    This is a fabulous article, Harry. I’ve skimmed it and bookmarked it for more detailed scrutiny. I actually spent more time poring over inuit.css — fascinating. I put together a piece on organizing your CSS in my “how-to” site for beginning designers, based on work by Rob Glazebrook, Douglas Bowman, and Tom Fadial and tweaked by me. Interesting to see the similarities and differences between that methodology and yours.

  5. 16

    Single vs multi-line CSS debate is pointless since you shouldn’t be using a CSS/HTML editor that can’t format the code with single click or keyboard shortcut :-p

    I think ordering properties (often being done by a css compressors) is a crime against humanity. In my opinion it should be divided into logic structure corresponding to the structure of the site.

  6. 17

    Christophe V.

    August 26, 2011 3:26 am

    Not sure about the “@import” usage :)

    Same thing for the internationalization of selectors (maybe if it’s really necessary if you have not the possibility to change them in HTML code), it will do too much unused and useless selectors in CSS.

    But great for the other parts, i agree with them ;)

  7. 18

    One thing often overlooked by CSS developers (and used by programmers) is the practice of splitting large chunks of code into multiple smaller files. Often it’s a necessity just to keep a code base maintainable.

    Most CSS preprocessors can automatically concatenate multiple files for you so you can use as many files as you like locally while only sending one file over the network.

    • 19

      Not entirely so:

      1. Maintainability is now best handled through preprocessors (SASS/LESS)

      2. OOCSS best-practices now state you should have a minimal amount of files

      3. By doing so there are less server requests

  8. 20

    Interesting, I never really thought about the multi-line topic that way before – something maybe to reconsider in future projects. I was definitely more of a fan of the single-line coding but can see your point…and may have to try it. good article!

  9. 21


    August 26, 2011 3:34 am


    An excellent (and in my case) timely reminder of good CSS practice…

    Just tidying up some CSS myself, and reminded me to “leave more comments!”

  10. 22

    Niels Matthijs

    August 26, 2011 3:37 am

    A decent write-up of the different styles of css coding, but the overall incentive of the article is not really reached in my opinion.

    You give a some good arguments for your preferred style, but they are hardly convincing for those who prefer a different style of css coding. You might like white-space in your css files, I for one don’t. Why do I not like it? Because it makes it harder for me to read. I absolutely hate single-line css and find it tiresome to work with.

    The biggest difference between our preferences lies with the proposed division of your css file. I prefer to group css by component. Together with single-line coding it’s quick and ease to see how a group of selectors form one visual component and how the css works together on multiple levels of html. I tend to group my css in component sections (like navigation, tables, basic frame, headings, …) and group all separate components underneath. That just doesn’t work very well with your proposed way of writing css.

    User preference is a pretty blocking issue when trying to come up with a global best practice way of writing css, which probably should and could not be solved on coder level. I think it’s more interesting to look at our coding tools and find ways to easily switch between different coding styles. Going from single line to multiline shouldn’t be all that hard to implement, having that build in to our coding tools could solve many issues.

    • 23

      Whitespace is fine for development, when you deploy your CSS you should always be minimising and gzipping it anyway so what is output isn’t the full local development version anyway.


    • 24

      Interesting proposition (ok that sounds like SPAM.)

      I’d love to see a simple text editor that has that switch between single and multi-line functionality for CSS files. I wonder how it will handle the line numbers and svn, etc.

      This should be on the to-do list of some developers. Or is there such a tool already?

  11. 25

    Very interesting article. Thank you for a nice reading. I am more a graphic designer than web developer but sometimes I have to sit down and code up a site or two ;) Since I don’t do it often and there are times when I have to go back to some previous css files, this set of advices you gathered here is also very helpful for those who commit occasional coding even if only for themselves. Believe me, opening your own messy file you wrote four months ago can also drive you bananas ;)


  12. 26

    It’s not about CSS – article is great, and there are many tools to help, so you… well, I don’t have the excuse not to do so, – but I have problem with HTML in that regard: for example, if you write every list item <li> on new line, then with display: inline-block there are spaces between them. float is unnecessary and add complications. Do I missing something?

  13. 27

    Nice article, readability of code is important for both the developer as well as anyone else who might read it .

  14. 28

    Great article. I find it useful to semantically list the colors and their hex equivalents in a comment, like /* red:#791302 grey:#5f6460 */

  15. 29

    Don’t however, forget who the code is for. The browser … well, ultimately the benefit of the user of the browser. And as such the end product seldom has direct connection to the production … look at many things we purchase without this actually being a problem: packaged food might include ingredients but not the actual recipe, clothing does not give instructions on how the fabric and peices were actually made and assembled, houses and cars don’t come with anything of the sort either … much of production is lost when it gets to the end user.

    When you stop to realise that ‘others’ in css authoring actually encompasses both end-users and developers, you will realise that different priorities are needed at the different ends. The two seldom are the same and that is fine. We can live with that, because we are.

  16. 30

    Brad Czerniak

    August 26, 2011 4:12 am


    Ordering declarations alphabetically is like ordering CDs by title alphabetically (not by cover brightness). It’s useful, even if colors/sizes/arbitrary groups are not together because firebug auto-sorts them alphabetically. By enforcing that order in the file itself, it makes maintaining the CSS that much easier.

    • 31

      @Brad Czerniak I couldn’t agree with you more, and that is exactly the reason why I order alphabetically. Chrome also does this auto-sort. The other thing you gain with alphabetizing is the enhanced readability – you can find a property of an element quicker when you know everything is alphabetized. Additionally, the other argument I have for alphabetizing is that there is no other easily-identifiable standard for sorting. The author suggests with categories such as Box Model and Color, but where does one place elements that commonly consolidate multiple properties, such as background, border and font? Each of those can contain Box Model and Color elements.

      • 32

        Bryce Pelletier

        August 26, 2011 6:46 am

        I don’t pretend to be any type of authority on css practices, but I have to agree with Brad and Adam on the alphabetical sort. Firebug (for any browser) as well as Chrome all sort alphabetically. This just makes it easier when coding to just make changes in firebug then copy paste when you get what you like. You can also identify what your looking for faster once it becomes second nature; which I found doesn’t take long at all. I made the switch from box-model order to alphabetical a few years ago and honestly I wouldn’t switch back. Alphabetical makes finding your property faster and more reliable. At least from where I sit.

        • 33

          I don’t get why you would sort your code alphabetically… When I’m looking for a certain element/selector I just Ctrl+f it. That’s even faster than searching through your alphabetically ordered code by hand ;-) By doing this I can sort my CSS in another way that’s also useful but not automated by my editor.

          • 34

            They aren’t talking about sorting selectors alphabetically, but the properties within the selectors, like font-weight, border, etc.

    • 35

      I agree with Brad on ordering declarations alphabetically. Mr. Roberts makes an apples to oranges comparison here, and ordering declarations by groups is more arbitrary than alphabetically sorting the declarations. In that context it’s not meaningless as Mr. Roberts suggests.

      • 36

        Alphabetical ordering drives me nuts. If I am working on a particular section, I want all the CSS for that section within reach. With alphabetical ordering I may have to move back and forth between line 10 and line 1417 just to get a slider and it’s overlay shaped correctly. I’m wasting half my time scrolling up and down…

        Additionally, there is so much disparity between how folks name their classes and IDs. If everyone sorted alphabetically then a header div could be located anywhere in a file: #header, #top-section, #upper-container, #etc.. There’s no consistency.

        • 37

          @ Don Elliot

          They don’t mean ordering the classes and IDs alphabetically.

          They mean naming the declarations within a class or ID, e.g. background, border, margin, width, etc.

          • 38


            Well if that’s the case there’s an argument for it. :) In my early stages when I was modifying WordPress themes instead of building my own I ran into seemingly countless stylesheets which were literally organized alphabetically by class and ID, it boggled my mind.

            Thanks for the clarifying!

  17. 39

    It’s all well using multi-line css and @imports, but if you’re building a site that needs to be fully SEO friendly then past experiences has found that @imports in CSS are not all that good and multi-line CSS gives you a slower rendering speed. I know its only fractional but if clients are looking to get good search engine results then every bit of code, html, css, regardless of whether people can read it easily; should work for what’s best for the site. But opinions are neither wrong nor right :)

    • 40

      A compromise is possible here, though – minify the beautiful multiline whitespaced CSS before uploading the spreadsheet to your live server, and keep the nice copy locally to work on…

  18. 41

    The most important skill is being adaptive. There are a number of ways to code CSS and great coders are those that can come into any project and immediatly start using whatever guidelines that business has.

  19. 42

    Comments are King, indeed. The article is spot-on, but I love that illustration! :-)

  20. 43

    “we get into our little bubbles, writing CSS with only ourselves in mind” ~ Guilty as charged (and by association too)!!

  21. 44

    I love this line.

    they’re no more right or wrong than I am. Taste is taste, and consistency is what matters.

  22. 45

    Great article!
    I’ve always been struggling with keeping my CSS clean en structured, but there are some great tips in here i would love to give a try!

    I do like the method of using @import and different stylesheets for each section/page for the larger projects. This is a easy way of structuring and when the thing goes live I tend to compile it to a single css the achieve better performance.

  23. 46

    spacing and indenting… thing that we need to have in any code.

  24. 47

    Developer Guy

    August 26, 2011 4:52 am

    Development has come a long way and often comments are now frowned upon, it is generally thought if you need a comment then you code wasn’t obvious enough or well encapsulated. I often write another method describing what I wanted to put in the comment and then encapsulate the logic in that, for example

    public void Login(string username, string password) {
    // check users login
    if (username == VALID__USER_NAME && password == VALID_PASSWORD …

    Would become
    public void Login(string username, string password) {
    AuthenticateUser(username, password)

    Bad example sorry, but why can’t CSS go this way with mixins now being available in CSS3, Compass and Less etc, etc. Instead of writing a comment to say to make scrollbar appear, write a method, use variables for colours, etc, etc

    • 48

      I can see the point being made here. If you name your classes well, it makes comments less necessary – and comments go out of date fast, which makes it confusing when the comment says the CSS is doing something that it isn’t actually doing anymore.

    • 49

      I think the main reason most css coders are averse to mixins and less or sass is you have to compile the code when you change something.

      And some of us have this “tweak-by-eye” kind of approach where you switch just one line-height by 0.1em and want to see results instantly. — something which isn’t fun to do if you have to compile the code first.

      Perhaps the problem is css is also a “design”-related code. Meaning, you can get the semantics right, the cascading of classes, etc by planning or logic but as for the exact property values (ie color, spacing, margins, etc) there’s a certain “guessing” feel to it that can’t be solved by planning. So there’s a lot of one-line editing that has to be done just to get the right “look”. And as I’ve said, it’s not fun to have to compile a piece of code just to see if 0.1 or 0.2em is better.

      • 50

        There is less.js with “#!watch” feature, so you don’t need to compile anything, or endlessly pressing the f5. ;)

  25. 51

    Thank you for writing this up! The most important line in the post is ” always code like you’re working in a team, even when you’re not.” I believe in this, to my core. Personal side projects that would not go on if you got run over by a bus are the only projects that you can really consider will only be coded by you. Anything related to a business could have someone else working with it at some point.

    You make some great points, but when you get into organization you end up doing the same thing that you suggest against in the beginning. To say organizing CSS alphabetically is like organizing cds by their cover color justifies your point but it’s not a fair argument. It’s like organizing CDs alphabetically. So, anyone that sees your CD collection can find a band by it’s name. They don’t have to know genre and they don’t have to decide where dubstep fits into the mix if they want to add a CD. It’s the same for CSS. Your friend that talked to his duck, is there a better chance that the duck understands your friend’s interpretation of DOM structure or the alphabet?

    In writing CSS for other people, you have to let loose of your preferences and look for guidelines.
    Why tend towards multi-line? Well, because the debuggers do (Firebug, Webkit Inspector, the thing in IE that shows CSS)
    Why tend towards alphabetical? Firebug does. (Webkit Inspector doesn’t and they don’t follow any type of grouping that makes sense to me. Find a complicated element on a page and open it in Webkit Inspector and Firebug and see which is easier to find something to change.)

    All in all, this is a thought provoking article and I really appreciate it. I just wish you would keep pushing a little bit more of an open approach. Logic is so different, person to person.

    • 52

      Matt Berridge

      August 26, 2011 7:15 am

      About the organisation argument…I am going to stick with music but use my own analogy of a DJ.

      DJ’s (also creators!) dont tend to order their songs alphabetically by artist. They mainly order by genre so that when they need a certain type of track they can find it most easily. Surely it’s a similar thing with CSS?

      I suppose crudely *anyone* looking would prefer to order alphabetically. Those who understand their craft (music genres or DOM structure) perhaps wouldn’t. Who are you coding for at the end of the day?

  26. 53

    Very good article, I am forwarding to my team, but I have to strongly disagree with one thing. WHITE SPACE IS NOT YOUR FRIEND. It is much easier to read code and understand groupings if you have less whitespace between lines. Whitespace in code should be like whitespace in regular writing. When changing ideas, break the paragraph. When changing the thought break the line.

    • 54

      I disagree with the delegation of whitespace to non-friend status.

      “Whitespace in code should be like whitespace in regular writing. When changing ideas, break the paragraph. When changing the thought break the line.”

      How does that NOT make whitespace useful?

      The point to whitespace is to separate different groupings and “visually” group together similar objects. Learning to use whitespace includes knowing when NOT to use it. Of course the author didn’t mean for us to add an extra line after each property. :)

  27. 55

    Great write up. Thank you.

  28. 56

    Great write up. I completely agree with your take on comments although I think your missing one important piece, the prolog. The prolog is a large comment at the top of the file that gives a description of the file, when/who it was created, and a listing of updates. I use this to track my history of changes in the file. This helps me in the future to understand what changed since I was last in the file or why I made a change in the first place. It is also helps me understand who else was in the file making changes.

    The other point to make, that we should really be “building” our CSS files. This removes the extra comments and tidies up the CSS statements. In addition to reducing the get requests, building the css will reduce the file size which is becoming more important as we move to low bandwidth devices like mobile. What you get is the best of both worlds, documentation during development and a fast website when you go live.

  29. 57

    Lots of good tips here, but this one I have to completely disagree with:

    “Ordering CSS alphabetically makes as much sense as ordering CDs by how bright their covers are.”

    You argue that “the initial letter of a declaration has no bearing on the declaration itself,” which is true, but that doesn’t mean that organizing them alphabetically is useless. To use your album argument, the first letter of a band’s name has no bearing on the type of music they play, so by that logic why sort your albums alphabetically either?

    Ordering CSS properties alphabetically makes as much sense as ordering *anything* alphabetically – so that you can quickly find what you need. By putting my properties in alphabetical order, I know that background, border, color, and font are near the top of my declaration; margin and padding are in the middle; text-align, width, and z-index are near the bottom; etc. It makes it quick and easy to jump around and find the property I need.

  30. 58

    Good article Harry, but as a long time developer (not a designer), I have an issue with your commenting.

    Comments like /* Colors */, followed by CSS that is obviously setting colors, are actually pretty useless. Comments should always convey some sort of useful information that would be otherwise hidden or obfuscated by the code. For example:

    /* This is used in the menu system. */


    Dark Red: #663a26
    Off-White: #fcfaf8

    • 59

      Harry Roberts

      August 26, 2011 6:01 am


      This is my mistake here; I wasn’t intending for those comments to remain in the file, I was merely marking them for the reader. I will address this :)


  31. 60

    Ordering CSS properties
    I found your analogy for this to be funny as most people would order their music alphabetically.

    The biggest advantage is that you can quickly scan and find an item. It’s immediately obvious how all the items are ordered, making it easy for someone else to use and reducing the amount of WTF moments.

    As the order is simple you can also tell if something is missing or if it already exists (you don’t have to double check that it is not further down in another group/type/relevant section). In CSS this prevents people adding duplicate properties which I have seen happen a lot when not ordering alphabetically.

    Over all I guess using an alphabetical system makes the most sense as everyone will understand it and its the fastest way for someone to find the item that they need to change. Lets be fair we will spend way more time editing than creating CSS.

    Given my opinion I actually think ordering CSS by type/relevance makes as much sense as ordering CDs by how bright their covers are :)

    Agree with just about everything else in the article, nice write up.

  32. 61

    Good read.

    I think a mix of single line and multi-line CSS is best. For example, for most properties single line would work great, however for font-face and other properties that require more code, multi-line would work better.

  33. 62

    Jakub Navratil

    August 26, 2011 6:05 am

    Very good article, personally it fits all what I use. But I dont agree with organizing style informations by relevations to selector … so in H1 font is first nad in DIV font is last for example.
    This is only complication I think, because anytime you look at style, you expect box-model properties be on start. I always sort styles like this:

    position / float
    box model
    font, text, color
    … others like box shadow, transformations, etc. …
    background at last

    And why?
    Because position is most important for me I thing, is there absolute or float: left? When I use float I immediately know that element is block.
    Thank check box model with overflow, personally I put line-height under height definitions, because many times its same.
    Than some content styling like texts etc.
    Background is specific, because when I develop, I always use solid colors to position elements on right place … so background is one of often used property and for better organization I just put it on the end.

    Any tips?

  34. 63

    Aleksy V Zapparov

    August 26, 2011 6:07 am

    No offenses, but it looks like you have reinvented disabled brother of LESS, or similar. Trying to make structure of file better suitable for one particular editor is not a solution IMHO. Anyway you have noticed in the beginning of your article: “We are selfish by nature; we get into our little bubbles, writing CSS (as amazing as it may be) with only ourselves in mind.” – I absolutely agree, and I guess your proposal only proves your statement.

    I believe it’s better to have well structured files like sources of binary application. So it will become easier to navigate through them. And to “fight” with restrictions and ugliness of CSS there are few awesome tools like LESS and so on. So you can simply write small make task to build final variant of your css file (even beautified) before deployment or testing.

    And once again. That’s only my own opinion. :)) And I assume that lots of people will find your proposal reasonable, but I don’t :)) Especially that idea about shared attributes… If it’s the only way – then you have to define them BEFORE other statements to allow easier reading of the file – at least I read files from top to bottom. With proposed way I need to read file top-bottom-middle-bottom… :))

  35. 64

    Also, indent! Your CSS addresses a DOM structure, you can help make your intentions evident when you indent your css instructions.

    ul.list {
    [tab]ul.list > li {
    [tab][tab]ul.list > li > a {

    Now, this larger block is portable, and clearly illustrates that you’ve created a little mini “widget”. Which is really all you’re doing in CSS.

  36. 65

    I agree with the multi layer format so much easier to read and is more logical too when trying assess things. Ive learned a lot thing from working with developers/programmers on formating code so that it is readable and makes sense. As far as what I’ve been able to take from working with them and merging their suggestions with my sense of logic, I like to layout my CSS in the same order as the sections of the html markup and the design/look of the site as follows

    /*HTML Reset*/

    /*General styles*/
    h, font tags etc.

    /*Header Area*/
    header style

    nav styles

    /*Content Area*/
    content are style

    /*Section 1*/
    styles here for section 1 arranged in the same fashion as it is depicted
    /*Section 2*/
    styles here for section 2 arranged in the same fashion as it is depicted
    footer styles

    This makes it easier for me when trying to make modifications, I can reference sections when I search (crtl f). It works well for me and keeps me sane hopefully the same for the others ;)

  37. 66

    I learn something new about CSS every time I read your posts, Harry. This is a fabulous article. And inuit.css just keeps getting cleaner and better!

    Rating: 10/10

  38. 67

    Yeah I agree with the readers who disagree with the author’s notion that alphabetical ordering is illogical. The author’s comparison is weak: alphabetical sorting is objective and universal whereas sorting by colour brightness is purely subjective. Otherwise the article is good.

  39. 68

    Hey! Great article, is always good to see how css coders write their code, but we have some mixed opinions.

    – Comments: Why is everyone so worried about comments? I think that a well written code is always self explanatory, since we get to choose our class names .top-nav will always respond to a top navigation, there’s no need to wrap that between comments. I have also a deep hate towards multiline comments. /* Top Navigation Menu */ is just what we need. Also single attribute commenting should only be used for specific cases, like ie6 fixes or so, the rest of the code is, again, self explanatory: #fff is white, and will always be.
    – Multi-line: Ok here I know is a matter of taste, but I found that writing single line css helped me get a good vision of cascade styled code, being able to wrap my code much better (avoiding, for example, unneeded comments). I understand what you say about version control, but almost every text compare software will show you specific changes on every line (GitHub won’t though).
    – Ordering CSS properties: I used to code my css in a more “intuitive” way, but I learned that it was only intuitive for me and some people that coded css like me. So, ordering properties (alphabetically) is: first of all easy to identify, when you start reading a code you’ll notice that at first sight, and will also make searching for properties more easy, padding will always be between margin and width.
    – About splitting the code I also think one single file is better for everyone, but there are nice solutions for those who work with separated files. Where I work we actually have a separated file for the homepage (with reset and generic data) for better loading and another one for the rest of the content. Of course we need to combine both for the rest of the content, so we use a script to concatenate both files into one. And we always minify that code :)

    Hope someone will take all opinions and use the best of both :)

  40. 69

    verry good read !

    i was looking for some good advices how to write better struktured css and found it here.

  41. 70

    Nice thoughts. I like the table of contents, and I also despise alphabetizing the declarations.

    Some grid related suggestions:

    You don’t need to worry about removing margins from the last column in a group of columns if you make the content responsible for all the gutters. Everyone already creates the vertical gutters with content elements, so why not do the same for your horizontal spacing? IMO this makes it a lot easier to define column widths and backgrounds. It also makes for easier nesting of columns.

    Although I really like the modularity of grid systems, I’ve moved away from classing my columns with explicit grid divisions. Now I use a basic grid approach with more generic proportional classes that can be matched to whatever grid my CSS assumes (in comments, of course). So if I were to switch to 16-column from a 12, no need to change the HTML.

    ex: class=”col-2v3″ (2 vinculum 3, or 2/3, since 2of3 is ambiguous)

    Again, good article.

  42. 71

    Demetrius McClain

    August 26, 2011 8:18 am

    I’m an avid believer in single-line css. I started out using multi-line and it just wasn’t preferable to me. I believe in sectioning my css. The first piece of css I write will cover site wide components and will be named accordingly, then I go page by page making it easy to locate the code for a specific page. I agree commenting is necessary for complex sites but believe sectioning is adequate when dealing with something simple.

  43. 72

    I agree with @Matt I love indenting and nesting, just like we all do with HTML. Since comments strip spaces, I’ll demonstrate with DASHES in place of spaces/tabs:

    –div#parent div#child{

    I find it so much more readable/scannable this way.

  44. 73

    Matt Berridge

    August 26, 2011 9:07 am

    Another nice tip is to put a specific character at the top of each comment flag for a section block that won’t be used anywhere else in the stylesheet.


    /* —————£
    1. Layout
    —————– */

    That way you can use your text editor’s search function for that character and quickly jump down to the top of each section.

    • 74

      Just search for —– ?

      Saves you the ugly character and remembering it. Apart from the fact that non-UK developers won’t have a £ within easy reach.

      • 75

        Matt Berridge

        August 28, 2011 6:10 am

        Using “£” was just an example as I’m from the UK. It could be anything (I use @ because I rarely use @import’s in my main style sheet.)

        If you search for “—” , you generally have comment flags above and below the title, or other comments / flags in that format elsewhere in document.

        Call me lazy but placing something at the top of each section listed in the contents (and only using a single character) simply makes it the quickest to search. The aim is to jump directly up/down to the primary sections in order.

        Just realised Harry had his section title as “$Type” which is presume is for this exact reason. $ probably makes most sense as it’s used in development everywhere.

  45. 76

    Good write-up, Harry. Some useful tips in there.

    But please stop using the “ordering CSS alphabetically is the same as ordering CDs by colour” analogy. It’s a very skewed (and illogical) way of getting your opinion across.

    I have no problem with your personal preference when it comes to ordering CSS properties. I would just like to see an unbiased reasoning behind it, which isn’t _just_ your personal preference. Especially when the surrounding article is about writing clean, developer-friendly, consistent CSS.

  46. 77

    Martin Doktár

    August 26, 2011 10:59 am

    Each line of comment you write is a small step closer towards admitting you write bad code.

  47. 78

    Very good article! Thanks Harry.

  48. 79

    Though, frivolous, I find a combination of Single and Multi line to be the best. What ever is the easiest to read. Sometimes I include an index at the top of the document if the document is very large, which also includes @Matt Berridge’s mentioned technique of jumping to sections. This can be removed at production.

  49. 80

    Nice article!

  50. 81

    Adam Lapczynski

    August 26, 2011 1:17 pm

    I personally can go either way; single-line or multi-line, but I do agree with going the multi-line route for team projects, or developing non-personal projects. When it comes to personal however, single-line is my preference.

    Like Jakub stated, I order my css:
    “position / float
    box model
    font, text, color
    … others like box shadow, transformations, etc. …
    background at last”

    And when it comes to single-line, keeping order in your css is key, otherwise I wouldn’t bother coding single-line. But for me, it works, because I know what to expect in which order. What I love about single-line is the way styles look when related styles are grouped together.

    .header { … }
    .header ul { … }
    .header ul li { … }
    .header ul li a { … }

    Although this isn’t how I normally target/structure descendants, it’s just a visual to support what I mean about grouping.

  51. 82

    Hi there.

    There doesn’t seem to be a definitve way of writing css, and there might be one or two things still to learn for all of us…

    Within my own stylesheets I favor the single file approach, I do order and indent the ids and classes according to their nesting in the corresponding html file.
    My attributes are kept together by function, like margin border padding, or display position top left width height etc. I do prefer multiline attributes, but there are times where some functionality just needs to be one line, like image replacement for menus for example. Np++ array selection FTW!

    Oh, and I like beautiful syntax highlighting and have to see my code green on black, otherwise I just can’t see anything.

    Towards perfection, mtness.

  52. 83

    Great article Harry – thanks a million!

    I work with a team of devs but one day someone else will have to take over and i try to code with that in mind!

    What I have learned from the devs though is that comments are a no-no now, not so?! Individual classes should be completely legible in their own right. A comment only implies a lack of clarity in the class.

    As others have pointed out, this will become more and more common when we all work out how to use Sass properly!

    As for alphabetizing – are you guys nuts?! Give me a nice
    /* —————
    Bunch o Headings
    —————– */
    anyday! Ctrl ‘F’ is a great man!

  53. 84

    Thanks for your article Harry and
    Thanks for all those very interesting comments.
    I’ll try to find my way.

  54. 85

    Chono Hegelund

    August 27, 2011 12:22 am

    This is a great recap …

    I also prefer multi-line css .. it speeds up the workflow so much when jumping to line – landing straight in the element/value you wish to edit/enter. Also i find it much more easy to keep an overview – reading multi line instead of sinle line code – same as HTML, JS and so on.

    If using single line, first i would have to go to the line and and then using valuable time to work my way out to the specific element.

    Also keeping all code in one doc is much appreciated – it slows down workflow a great deal having to switch between different docs, keeping track of what is what.

    Lastly, intuitive structured code by sections and elements over alphabetical … alphabetical makes no sence in my workflow also since there is no standard rules how to define classnames/ID – code structured by sections and elements at least offers some standard intuitive guides ..

  55. 86

    Hello there, nice articles every time i browse your awesome site!

    I think these rules for creating a stylesheet that everyone simply understands, is totally necessary! But in my opinion, the bilingual thing, for americans and for example brits, is a bit too much. It takes more time to give some tags more than one class, than to require that a brit in most of the cases, only has to add or remove a letter just in mind. The value “center” is also american english and not “centre”.
    American english should be the only language in writing CSS =)

  56. 87

    Note that reducing the number of http requests is not one of the most important rules anymore, cf a doc of google mentioned by steve souders on his twitter account recently.
    But that’s for few big files, too few small files are definitely not recommanded.
    What i do is having one css file for all the common parts of my website, and one for each specific section. It’s not .css files but php files which allows me to make server-side includes, use functions, define constants etc. But this is true for me only, because the visitors are seeing a compiled version of it : i have a deployment option that gets the result, minify it and put it in a regular css file.
    This deployment tool creates multiple css files customized for each major revisions of browsers, using the best technics available for each of them : for instance gradients use css3 where available, dxtransform on IE when possible, or generate a PNG file that is linked using the common url way, or embed it as base64 data url into the CSS.

    It took me a few days to write it, but it saved me much more time since then. And when a new browser revision is there, i simply modify the generator so i can use its new features from day one.

    Use a script language for your CSS… You’ll never regret that choice.

  57. 88

    This isn’t any more standardized than any other person’s subjectively methodical approach. Just decreed from the smashing magazine soap box. Also, I agree with other comments about this statement being pretty inaccurate, “Ordering CSS alphabetically makes as much sense as ordering CDs by how bright their covers are.”

    More like, ordering CSS alphabetically makes as much sense as ordering your CDs alphabetically. Turns out that actually makes quite a lot of sense! And to be clear, we’re talking about declarations within selectors, not alphabetizing all the selectors in your CSS file.

    You want to think like a programmer about CSS? Don’t take it so seriously :-P

  58. 89

    If you want to have maintainable CSS use SCSS:
    Then you will have true variables for your CSS, ability to have your code in nice modules, but compressed CSS file for production, mixins, functions, nesting, etc. etc.
    Just try it. It will be the best thing you ever did for your CSS development.
    Don’t use grid frameworks. Class names like “grid-4” are as bad as “.centered” and don’t belong to your code. Once again, with SCSS you can have your grid without those
    class names polluting your HTML (@extend).

    As for this article: don’t comment everything. Only comment things which are non obviuos. There is no good in having “This sets font size” comment above font-size rule.

  59. 90

    Douglas Bonneville

    August 28, 2011 6:13 am

    Great article and great points. I do a lot of these too. But…

    I’d argue about ordering by alphabetical or by section or by…anything.

    I have found that on a team, what people think goes in this section or that section is arbitrary over time. There are continual additions at the end of the CSS, and random new sections dumped in the middle of file that one developer thought made sense, but didn’t make sense to me. The end result is a mish-mash over time.

    What to do?

    By the time a site has gone to production, I no longer care in the least how it’s ordered, because if I add something new, it goes in the bottom. If I update something, I’m just firebugging it and getting the line number and jumping to it.

    Therefore, I think it makes sense to develop the site with a section-style ordering. After the site goes to production, it really doesn’t matter because new stuff goes at the end (or some arbitrary place in the file) and updates and tweaks go where they go by line number. It really doesn’t matter when you are searching and Firebugging after the fact.

  60. 91

    dhiren suthar

    August 28, 2011 7:52 am

    its awsome :) very useful

  61. 92

    Great write up Harry, thanks :)

    Its one of those things that we take for granted, Isn’t it ? .
    Same goes for coding as well. Write for others .

  62. 93

    Nice Article! I always try to write CSS by sectioning and comments. It all goes pretty nice at the beginning but as the project becomes bigger, it all goes wayward. :)

  63. 94

    Great article and great points. I used these points in every project.

    Normally at the time of developing I used same thing, but when time come to deploy on server I always use single-line CSS which save lot of file size.

    Anyways everyone have different format of writing CSS. But take care next person can understand your CSS in easy way.

  64. 95

    Great read. The premise of this article is true, write the code that any front-end dev can read and interpret efficiently and everyone wins.

  65. 96

    I personally use both, multi-line and single line.

    If the selector will have more than 3-4 properties assigned, I use multi-line, if it ‘s less than 3 properties, I use single line.

    So for example:

    a.option {
    color: blue;
    text-shadow: 1px 1px 3px #333;
    text-indent: none;
    font-size: 1.2em;
    a:option:hover { text-shadow:0 0; }

    And I definitely think there’s no need to do i18n for other languages… my native language is spanish, my CSS would be crazy, and probably would weigh a lot more.

    Btw, do you know if the attribute selector grid approach would work on IE?

    Thanks, good article! :)

  66. 97

    Nice article!
    I do also support the multi-line coding.

    When I started coding I started using single-line, after a while, I realized multi-line is just much more organized and easier to read.

    Thanks for sharing.

  67. 98

    I disagree with the advice given here:

    I read:

    | color: #666; /* light gray is nicer to read than black. */

    That comment adds clutter. And the `color` with your background color (#fff) will be very hard to read, causing usability and accessibility problems, particularly with the reduced font size you have chosen. What happens when somebody has the good sense to darken the color to say #333 or if the scheme changes to have a hue? Do you want to updated the meaningless clutter comment, too? I’d just delete it.

    Copy’n’pasting all css into one file as a performance optimization is problematic, as other commenters have pointed out.

    One-big-file means reduced modularity and increased code bloat. With cohesive modules as files, it is very clear what the scope of the file is and it is not hard to find where that file is being used. With one big file, it is not as easy to discover unused selectors, which, ironically, end up being identified not by a well-named file, but but by a geographical location within one badly named file (e.g. master.css), with discussion such as “Oh, that piece of code, yeah, that’s about 80% of the way down, around line 900”. And then “is anybody using this selector?” A one-file approach can work for simple sites, but it doesn’t scale well to larger projects.

    If you want to reduce HTTP requests, you can use a few approaches. I use a build process with ANT and YUI Compressor. I have explained how to do this on c.l.js Julien LeCompte has also done so on his blog.

    There is so much bad advice on the web already; why add more?

  68. 99

    Adham Dannaway

    August 29, 2011 3:09 pm

    Personally, I’m a fan of single line CSS with indentation for child elements. This makes it much easier to modularize your file and see dependencies. I actually think it looks nicer too, but that’s just me ;-)

  69. 100

    Good post, I certainly picked up a couple of good ideas.

    We’ve been working on this for a very long time. At my work we’ve had iteration over iteration of how CSS should be structured and organised. It has unfortunately fallen victim to a bunch of Java worshipping developers and became a fragmented monstrosity, with each site having a minimum of 15 or so CSS files (although served in a merged and cached form) using vague OO-style naming/structure for files an sub-folders.

    I have a more straight forward approach, some of it being similar to your description. For eg. the sharing of common properties. However, I always have declarations with shared properties at the top, since you can not easily override properties in exceptional cases. It makes more sense from the cascade’s point of view.

    As for formatting, I have written a blog post – – that describes the basic idea behind how I approach this. I believe that a mentality of grouping and classing things (in naming and structure) is the basis for good CSS.

    Also, I believe the same semantic structure should govern the CSS as the one used in the HTML markup. It’s logical, and helps take better advantage of the cascading achitecture.

  70. 101

    Thanks for the article! What does this audience think about YAML or any other framework in this context?

  71. 102

    Carlo Rizzante

    August 30, 2011 2:27 am

    Thanks for writing all of this, Harry, it’s a great source of inspiration.

  72. 103

    It’s like you read my mind….

    Working as a team & having a format makes jumping onto each other’s projects so much easier. Every freelancer I’ve worked with has a different style of coding which is a problem for me as it makes editing there work long winded, so i created a guide doc to how we would like them to code their CSS (it’s a guide not rules).

    Wicked article
    Peace out

  73. 104

    Sandy Campbell

    August 30, 2011 9:16 am

    A comment now and then isn’t a bad idea, especially if it’s for code you might forget the purpose of down the line. But comment EVERYTHING? The only people who will read your CSS are people who understand CSS, so commenting on what size a font is, what color a font is, etc. is totally unnecessary and distracting.

  74. 105

    Internationalization here means Anglitization e.i. translating to English

  75. 106

    amit mojumder

    August 30, 2011 11:44 am

    there is no harm in single line CSS if you make appropriate comments and indent the child element styles properly. it may reduce the whole css file size dramatically and improve the site performance a lot.
    i prefer to use single line css with comments and love to keep the file size smaller.

    thanks for the article.

  76. 107

    Great article with some really good tips. Just to refer back to a conversation between James, Martin and Lea Verou earlier in the comments (and if anyone’s interested), after reading this article I decided to convert the CSS for my website from single line to multi line and add some comments, content list etc.

    The difference between the two files is:
    OLD: 375 lines – NEW: 1142 lines
    OLD: 19.2KB – NEW: 23.5KB

    So all in all not a huge difference in file size compared to a drastic difference in the number of lines, and considering this is a personal site I think I can live with it. Would be interesting to see the difference in file size on a much larger project though.


  77. 108

    “First, the reasoning: my number one tip for developers is to always code like you’re working in a team, even when you’re not.”

    The best tip I ever heard is “You should code like the person maintaining the code after you is a psychopathic axe murderer who knows where you live.”

  78. 109

    Cool article, interesting ideas on how to structure css.

  79. 110

    Scott Simpson

    August 31, 2011 6:15 pm

    If you are reading the CSS, you are doing it wrong. Firebug should tell you exactly which rules are targeting which elements. Excessive commenting is a waste of time, so is ordering your rules. I realize this could be somewhat helpful when creating a framework, but how many CSS developers are creating frameworks?

  80. 111

    I work on a CSS framework in my company, and here I use a indent system to organize the CSS. If the rule are more indented, it is more especifique:


  81. 112

    I was taught very early the value of having an extremely clean CSS file, and code in general. I tried editing my first ever css file a few weeks back just to see how I started (you should try it too) and it was awful, no comments, missing semicolons, all kinds of bad syntax. I take pride in keeping clean code, I guess that’s the downfall of us web professionals using WordPress-type CMS’ now because I don’t have 100% control over how the entire code is written. I normally take and customize the default twenty-eleven theme, but it still doesn’t look very pretty in a browser.

    A professor of mine always said: “If you died tomorrow, could somebody edit your code efficiently?” It’s a bit much, but it makes sense!

    Take pride in your code, organize it!

  82. 113

    Nice article. However, I do not agree with the extensive use of comments as comments has a tendency to not be changed when the code is changed, leading to inconsistency. More importantly is to have good self explenatory names.

  83. 114

    Check out

    block-independent method, much like your proposed in article

  84. 115

    Use comments at your peril. For a developer if you’re using comments in your code, then your code isn’t communicating its intentions. The best way is to write your classes and ids in a way that is self describing. I’ll give you it’s a little harder in CSS, us devs have classes, methods, properties etc that can be used to describe what’s it’s doing.

    The problem with comments is that they tend to rot. Someone changes the code but not the comment (You could argue this is about discipline but then by adding comments you’re adding maintenance). Then the comment doesn’t make sense, this can lead to confusion, people ignoring them and nobody trusts them. The only truth is the code, so make sure this makes sense.

    Use them but only if there’s no other way.

  85. 116

    Here’s an interesting approach formatting css

  86. 117

    I’m baffled and somewhat frightened by the suggestions in the article and comments that breaking up CSS into multiple files, using comments, white space, and multi-line property declarations is a bad performance practice. If you aren’t using a build script or something to combine and minify your CSS when you deploy on production you’re doing it wrong.

  87. 118

    Everyone should just work in SASS. This allows you to write long comments, use variables and break things up into multiple files without adding to the size of the final output css.

  88. 119

    Jorgen Kesseler

    September 12, 2011 6:13 am

    Nice article but do disagree a few points

    First “Comments Are King!”
    No they are not. I’m a front-end dev at the largest online retailer in my country and we hardly use comments in our CSS (and HTML and JS for that matter). If you code needs heavy comments to explain what it does, there is something wrong with you code. Code should be written in clear and easy to understand manner. Of course in CSS that’s a bit more difficult since there is no logic to it. But still you should use comments sparingly.

    Second “Internationalize Your Selectors”.
    Imo this leads to inconsistency, sometimes using “centred” and other times “centered”. When reading trough the HTML you might think they represent two different thing when, in fact, they don’t. CSS is in US English anyway so why not stick to that.

    Third “Be Pre-emptive, Think About Edge Cases”
    It is practically impossible to think about all possible edge cases. Just build as you need. Why add stuff now that you are not sure of using later? This leads to bloat and unused code.

  89. 120

    Derick Montague

    September 14, 2011 7:00 am

    I couldn’t agree more with your preference of multi-line CSS and the order of your declarations. Multi-line may make a larger file, but there are ways to min those files for quicker load. The importance is in readability and single line doesn’t allow for the code to be scanned quickly.

    Ordering declarations by importance and grouping makes the most sense to me. Actually, I tended to always start with the box model and then font and text and then others, but your reasoning for basing that order on the selector makes sense.

    Thanks for the great read and for sharing your insights.

  90. 121

    Some nice tips but you can also simply run it through or, they’ve saved me hours already!

  91. 122

    Michael Fokken

    October 13, 2011 10:31 pm

    I agree with commenting. Even in php, it helps a ton. I just forget to go back and comment my code. That’s why I try to do it as I go. However, I do try to limit my commenting because every character I type means it’s going to take that much longer.

  92. 123

    Artur Kwiatkowski

    November 5, 2011 5:04 am

    Great article! However I dont agree with the overal problem of multiline vs single line css – the only problem lies in your head! I prefer to write single line with some short comments (but only when they are needed). I think that good code should be written in a way to be easily understood by reading the class and id names by any html/css developer. This can especially be achieved if the design is constructed with good standards.

    If we work with SVN, CSS file developement and further editing should look like this and it really should be a standard in your head:

    1. some dev produces and delivers css file (single line format v 1.0)
    2. other dev receives it and needs to apply some changes
    3. your svn concerns goes here….

    In perspective of overal project process – editing a finished file is like grabbing the final product from the shop shelf and putting it back to the factory when it needs to be enhanced. You cannot leave the product on the shelf and make the changes in front of the clients – because thats not a professional behaviour – you need to redraw the product and process the changes in a proper way. So:

    3.1. You find the CSS 1.0 (single line)
    3.2. You apply code formatting by a software option (i think dreamweaver can do this) so that the CSS becomes multiline – we have now version 1.0-dev
    3.3. You commit this to svn
    3.4. You apply changes and commit the file to svn as many times as it needs (lets state that there were 3 changes)
    3.5. When the changes are applied, you make another version – lets say 1.4-dev
    3.6. You use an software option to reformat the CSS into the single line format
    3.7. You have now a 1.4 version which can reside on the production server.

    Voila! You have now range of changesets – 1.0-dev to 1.4-dev which are easily readable from svn logs but the production file is single line.

  93. 124

    > Ordering CSS alphabetically makes as much sense as ordering CDs by how bright their covers are.

    Uh, not really. It makes as much sense as ordering CDs *alphabetically*. Which is quite a lot of sense.

    What is important is the order, so that other people know where to find things.

  94. 125

    Reason why I prefer multi line css is because my code reading pattern. I want to read from top to down, not top-down-left-n-right — it’s becoming tiresome after some time.


↑ Back to top