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?

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.

A New Way of Thinking

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.css3 and working on a huge front-end framework at my job4, 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!

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 Payne5, told me about. That technique is called “rubber-duck debugging6”:

… 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

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.

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:

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:

Ordering CSS Properties

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 GitHub12; 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:

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

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:

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

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.

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 rules13 for a high-performance website.

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

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

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

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 {
[style]
}

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

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.

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">
…
</div>

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">
…
</div>

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

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.

Addendum

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

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.

Harry Roberts is a Senior UI Developer for Sky.com 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.

Related Articles

mtness

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.

0

52

Diarmozoid

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!

0

103

rigamarole

Chono Hegelund

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 ..

0

205

Chrizzle L.

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 =)

0

256

Joey

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.

0

307

mike

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

0

358

Rimantas

If you want to have maintainable CSS use SCSS: http://sass-lang.com/
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.

0

409

Douglas Bonneville

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.

Garrett

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.

Adham Dannaway

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 ;-)

0

919

Istvan

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.

Carlo Rizzante

David Martin

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

0

1123

Sandy Campbell

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.

0

1174

Milan

amit mojumder

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.

0

1276

Ash Robbins

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.

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.

Kristian

Scott Simpson

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?

Chris

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!

0

1582

Tore

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.

0

1633

mr. o

Tom Philip

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.

0

1735

Hannes

Usme Cah

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.

Jorgen Kesseler

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.

0

1939

Derick Montague

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.

0

1990

Rajesh Jha

Michael Fokken

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.http://whatiscss.michaelfokken.com/

0

2092

Artur Kwiatkowski

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:

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.

Subscribe to our email newsletter for useful tips and valuable resources, sent out every second Tuesday.

It's finally here. Smashing Book #5, our new book on real-life responsive design. With front-end techniques and patterns from actual projects, it's a playbook to master all the tricky facets and hurdles of responsive design. Get the book.Free shipping.

Fixing RWD issues can be quite easy — once you understand exactly why they come up. The Mobile Web Handbook will help you understand technical issues on mobile and how to deal with them effectively.

Hungry for more content? Over 60 eBooks are waiting to be discovered in our lovely Smashing Library. And guess what? You can watch Smashing Conference talks there, too.