Improving Code Readability With CSS Styleguides


Once your latest project is finished, you are very likely to forget the structure of the project’s layout, with all its numerous classes, color schemes and type setting. To understand your code years after you’ve written it you need to make use of sensible code structuring. The latter can dramatically reduce complexity, improve code management and consequently simplify maintainability. However, how can you achieve sensible structuring? Well, there are a number of options. For instance, you can make use of comments — after all, there is always some area for useful hints, notes and, well, comments you can use afterwards, after the project has been deployed.

Indeed, developers came up with quite creative ways to use comments and text formatting to improve the maintainability of CSS-code. Such creative ways are usually combined into CSS styleguides — pieces of CSS-code which are supposed to provide developers with useful insights into the structure of the code and background information related to it.

This article presents 5 coding techniques which can dramatically improve management and simplify maintainability of your code. You can apply them to CSS, but also to any other stylesheet or programming language you are using. You can browse through the references listed under the article — they containt further information about how you can achieve a well-organized and well-structured code.

You may also be interested in the articles

1. Divide and conquer your code

First consider the structure of your layout and identify the most important modules in your CSS-code. In most cases it’s useful to choose the order of CSS-selectors according to the order of divisors (div’s) and classes in your layout. Before starting coding, group common elements in separate sections and title each group. For instance, you can select Global Styles (body, paragraphs, lists, etc), Layout, Headings, Text Styles, Navigation, Forms, Comments and Extras.

To clearly separate fragments of code, select appropriate flags or striking comments (the more *-symbols you have in your code, the more striking a heading is). In the stylesheet they will serve as a heading for each group. Before applying a preferred flag to your code, make sure you can immediately recognize single blocks when scanning through the code.

However, this approach might not be enough for large projects where a single module is too big. If it is the case, you might need to divide your code in multiple files to maintain overview of single groups of code fragments. In such situations master stylesheet is used to import groups. Using master-stylesheet you generate some unnecessary server requests, but the approach produces a clean and elegant code which is easy to reuse, easy to understand and also easy to maintain. And you also need to include only the master-file in your documents.

[Master Stylesheet]

Project:	Smashing Magazine
Version:	1.1
Last change:	05/02/08 [fixed Float bug, vf]
Assigned to:	Vitaly Friedman (vf), Sven Lennartz (sl)
Primary use:	Magazine 
@import "reset.css";
@import "layout.css";
@import "colors.css";
@import "typography.css";
@import "flash.css";
/* @import "debugging.css"; */

For large projects or large development team it is also useful to have a brief update log and some additional information about the project — e.g. you can put the information about who is this CSS-file assigned to and what is its primary use (e.g. Smashing Magazine, Smashing Jobs etc.).

Additionally, you can include a debugging CSS-code to take care of diagnostic styling in case you run in some problems. Consider using Eric Meyer’s Diagnostic Styling4 as a debugging stylesheet to test your CSS-code and fix problems.

2. Define a table of contents

To keep an overview of the structure of your code, you might want to consider defining a table of contents in the beginning of your CSS-files. One possibility of integrating a table of contents is to display a tree overview of your layout with IDs and classes used in each branch of the tree. You may want to use some keywords such as header-section or content-group to be able to jump to specific code immediately.

You may also select some important elements you are likely to change frequently — after the project is released. These classes and IDs may also appear in your table of contents, so once you’ll need to find them you’ll find them immediately — without scanning your whole code or remembering what class or ID you once used.

[Layout] * body + Header / #header + Content / #content - Left column / #leftcolumn - Right column / #rightcolumn - Sidebar / #sidebar - RSS / #rss - Search / #search - Boxes / .box - Sideblog / #sideblog + Footer / #footer Navigation #navbar Advertisements .ads Content header h2 -------------------------------------------------------------------*/

…or like this:

[Table of contents]

1. Body
	2. Header / #header
		2.1. Navigation / #navbar
	3. Content / #content
		3.1. Left column / #leftcolumn
		3.2. Right column / #rightcolumn
		3.3. Sidebar / #sidebar
			3.3.1. RSS / #rss
			3.3.2. Search / #search
			3.3.3. Boxes / .box
			3.3.4. Sideblog / #sideblog
			3.3.5. Advertisements / .ads
	4. Footer / #footer

Another approach is to use simple enumeration without indentation. In the exampe below, once you need to jump to the RSS-section you simply use a search tool to find 8. RSS in your code. That’s easy, quick and effective.

[Table of contents]

1. Body
2. Header / #header
3. Navigation / #navbar
4. Content / #content
5. Left column / #leftcolumn
6. Right column / #rightcolumn
7. Sidebar / #sidebar
8. RSS / #rss
9. Search / #search
10. Boxes / .box
11. Sideblog / #sideblog
12. Advertisements / .ads
13. Footer / #footer
<!-- some CSS-code -->
[8. RSS / #rss]
#rss { ... }
#rss img { ... }

Defining a table of contents you make it particularly easier for other people to read and understand your code. For large projects you may also print it out and have it in front of you when reading the code. When working in team, this advantage shouldn’t be underestimated. It can save a lot of time — for you and your colleagues.

3. Define your colors and typography

Since we don’t have CSS constants yet, we need to figure out some way to get a quick reference of “variables” we are using. In web development colors and typography can often be considered as “constants” — fixed values that are used throughout the code multiple times.

As Rachel Andrew states5, “one way to get round the lack of constants in CSS is to create some definitions at the top of your CSS file in comments, to define constants. A common use for this is to create a color glossary. This means that you have a quick reference to the colors used in the site to avoid using alternates by mistake and, if you need to change the colors, you have a quick list to go down and do a search and replace.”

# [Color codes]

# Dark grey (text): #333333
# Dark Blue (headings, links) #000066
# Mid Blue (header) #333399
# Light blue (top navigation) #CCCCFF
# Mid grey: #666666
# */

Alternatively, you can also describe color codes used in your layout. For a given color, you can display sections of your site which are using this color. Or vice versa — for a given design element you can describe the colors which are used there.

[Color codes]

Background:	#ffffff (white)
Content:	#1e1e1e (light black)
Header h1:	#9caa3b (green)
Header h2:	#ee4117 (red)
Footer:		#b5cede (dark black)

a (standard):	#0040b6 (dark blue)
a (visited):	#5999de (light blue)
a (active):	#cc0000 (pink)

The same holds for typography. You can also add some important notes to understand the “system” behind your definitions.


Body copy:		1.2em/1.6em Verdana, Helvetica, Arial, Geneva, sans-serif;
Headers:		2.7em/1.3em Helvetica, Arial, "Lucida Sans Unicode", Verdana, sans-serif;
Input, textarea:	1.1em Helvetica, Verdana, Geneva, Arial, sans-serif;
Sidebar heading:	1.5em Helvetica, Trebuchet MS, Arial, sans-serif;

Notes:	decreasing heading by 0.4em with every subsequent heading level

4. Order CSS properties

When writing the code often it’s useful to apply some special formatting to order CSS properties — to make the code more readable, more structured and therefore more intuitive. There is a variety of grouping schemes developers use in their projects. Some developers tend to put colors and fonts first; other developers prefer to put “more important” assignments such as those related to positioning and floats first. Similarly, elements are also often sorted according to the topology of the site and the structure of the layout. This approach can be applied to CSS selectors as well:

	h1, h2, h3,
	p, ul, li,
	form {
		border: 0;
		margin: 0;
		padding: 0;

Some developers use a more interesting approach — they group properties in an alphabetical order. Here it’s important to mention that alphabetizing CSS properties may lead to some problems in some browsers. You may need to make sure that no changes are produced as a result of your ordering manipulations.

body {
background: #fdfdfd;
color: #333;
font-size: 1em;
line-height: 1.4;
margin: 0;
padding: 0;

Whatever grouping format you are using, make sure you clearly define the format and the objective you want to achieve. Your colleagues will thank you for your efforts. And you’ll thank them for sticking to your format.

5. Indentation is your friend!

For better overview of your code you might consider using one-liners for brief fragments of code. This style might produce messy results if you define more than 3 attributes for a given selector. However, used moderately, you can highlight dependencies between all elements of the same class. This technique will dramatically increase code readability when you have to find some specific element in your stylesheet.

#main-column { display: inline; float: left; width: 30em; }
	#main-column h1 { font-family: Georgia, "Times New Roman", Times, serif; margin-bottom: 20px; }
	#main-column p { color: #333; }

You remember exactly what you did and can jump back in there and fix it. But what if you made a lot of changes that day, or you just simply can’t remember? Chris Coyier suggests6 an interesting solution for highlighting recent changes in your CSS-code. Simply indenting new or changed lines in your CSS you can make recent changes in your code more visible. You can as well use some comments keywords (e.g. @new) — you’ll be able to jump to the occurrences of the keyword and undo changes once you’ve found some problems.

#sidebar ul li a {
     display: block;
     background-color: #ccc;
          border-bottom: 1px solid #999; /* @new */
     margin: 3px 0 3px 0;
          padding: 3px; /* @new */


CSS styleguides are helpful if and only if they are used properly. Keep in mind that you should remove every styleguide which doesn’t effectively help you to get a better understanding of the code or achieve a well-structured code. Avoid too many styleguides for too many elements bundled in too many groups. Your goal is to achieve a readable and maintainable code. Stick to it and you’ll save yourself a lot of trouble.

Sources and Resources


  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

↑ Back to top Tweet itShare on Facebook

Vitaly Friedman loves beautiful content and doesn’t like to give in easily. Vitaly is writer, speaker, author and editor-in-chief of Smashing Magazine. He runs responsive Web design workshops, online workshops and loves solving complex performance problems in large companies. Get in touch.

  1. 1

    I also like to include contact info at the top of my stylesheets, in case someone has a question about my code, or any other correspondence related to it.

  2. 52

    Excellent tips! I always match the order of my stylesheet with the order of my page elements for easy reference.

  3. 103

    Karol Adamczyk

    May 5, 2008 11:07 am

    Or simply use firebug…

  4. 154

    Last night, I was looking at my css code after a long break from it. What a mess! This will help better organize it hopefully

  5. 205

    I agree with QT above: The CSSDoc developers would be well-advised to learn about the techniques you presented here. CSSDoc is what I currently use simply because it mirrors JavaDoc and PHPDoc, which is a standard commenting technique to embed documentation (which can be easily extracted using appropriate tools). Using CSSDoc has saved me hours of time and allows me to format my CSS in a way that other developers can easily understand.

    Great article and thanks for sharing!

  6. 256

    Lol, in the examples light black and dark black, black is black, dont u mean grey?

    But nice article. I thought everybody did this, cause sometimes when u design sites the css will get so cluttered and when u return to the project maybe a month or 2 later u really have to relearn things.
    Also always use the same names to describe things.

  7. 307

    A great article. There are a couple of things I use to structure my css files. First I define the basic stuff ( body, h1…, links, forms etc ) then I write the basic layout structure and after that I write the other stuff. With a small site it’s a piece of cake remembering the meaning of a small part of the code, but the bigger the site gets I tend to make things messy . . . I think this article will help me to make this mess go away

  8. 358

    Great post, I have been using some of these tips, but the rest is quite useful , also putting them together like this is really helpful. Thanks, keep the good work

  9. 409

    1. Adding comments extensively will make a problem in larger CSS files where CSS will take a few seconds to load, I think it’s batter to make a separate file [e.g.: style_guide.doc] and add reference in your CSS file to particular sections in style_guide.doc.

    2. Add following sections in the style_guide.doc
    – Information about Project and Developers/Designers
    – List of CSS Files or other relevant files
    – Table of Content
    – Colors
    – Typography

    3. Group properties in CSS so that it’s easy to find and maintain styles of a particular section.

    This process may sound lengthy and many designers will take it as an unnecessary extra documentation work, but this is really useful when you are working on a large project with a team or when you are working on old projects created my others.

  10. 460

    Good points. Having a systematic approach to CSS and finding stuff later is a big time-saver. I see a lot of concern in the comments about file size, choking Validators etc., so here’s my take.

    In my opinion, CSS files on production servers need only be readable by the browser, not humans. Humans who have questions about my CSS can contact me and discuss it. There’s really no reason to waste your client’s and your audience’s time and capacities by having nicely formatted CSS just so a few people can educate themselves. If you want to educate people, do so explicitly (articles, tutorials, code examples etc.) but don’t abuse resources.

    Therefore, I keep the file sizes as small as possible and reduce HTTP requests as far as I can. That means:

    – use static external files (no uncacheable oh-so-clever on-the-fly php stuff)
    – strip out all unnecessary characters (i.e. semicolons, comments) and whitespace
    – shorthand notation for attributes, colour values etc.
    – use only one file per medium (“screen”, “print”, whatever)
    – no multiple @import directives (each one causes a separate HTTP request, contrary to popular belief)

    I have a simple build process involving a Python script that converts my various files into one, in the right order and does the stripping. That way, I can use the heavily structured and commented versions for development and the “built” version for deployment. If you’re proficient in just about any programming/scripting language that supports Regular Expressions, it’s a piece of cake. If not, you can still do it manually, e.g. use one of the many CSS minifiers/cleaners online and stitch the output together yourself.

    A classic “win-win”: You have a nice framework within which to develop your CSS and your users get the best performance from the live site.

  11. 511

    Jade Ohlhauser

    May 6, 2008 9:25 pm

    I like adding lots of comments as suggested in this great article. To reduce size I have an optimizer that strips the comments out of the deployed code:

  12. 562

    Some good ideas yea but in bigger sites with a lot of hits (like the ones i work on unfortunately) this all just creates a lot of extra bytes! I find its best to keep comments to a minimum (especially with the wonder of firebug these days) and i prefer to keep all CSS for a selector on one line, not only does this save bytes but i personally think it’s easier to read.

  13. 613

    thx.. this is really helpful

  14. 664

    Hello, this might be a really simple question for you guys, but I really need to know what means this line:
    font: 1.2em/1.6em Verdana, Helvetica, Arial, Geneva, sans-serif;

    Why the font size is like 1.2em / 1.6em ?? I normally use something like this:
    font:1.2em Verdana, Helvetica, Arial, Geneva, sans-serif;

    I guess these are 2 different values, but I’m not sure what are the values!

    Thanks in advance,

  15. 715

    @Edgar: Your question is pretty off-topic here, people don’t appreciate that and are likely to ignore you. Rather seek help on a relevant forum or, even better, start reading the specs — your solution is here.

  16. 766

    [Master Stylesheet]

    Project: Smashing Magazine
    Version: 1.1
    Last change: 05/02/08 [fixed Float bug, vf]
    Assigned to: Vitaly Friedman (vf), Sven Lennartz (sl)
    Primary use: Magazine
    @import "reset.css";
    @import "layout.css";
    @import "colors.css";
    @import "typography.css";
    @import "flash.css";
    /* @import "debugging.css"; */

    That looks good but is a very bad idea for two reasons :
    – the stylesheet wouldn’t be validated
    – safari (unlike IE or FF, haven’t tested other browsers) would stop parsing the stylesheet when encountering an “@”, causing your styles to be totally messed up

    why ? any @import or @charset instruction needs to be placed first in the sheet, even before any comment.

  17. 817

    Thanks for help.

  18. 868

    Jérôme Jaglale

    May 22, 2008 3:31 pm

    If you have a mac, use CSSEdit:

    It makes at least three of these guidelines useless:
    2: you can group your CSS by folders, just like files
    3: if you use the GUI to generate your code, you don’t even have to look at your code
    5: one shortcut and your file is indented as you want

  19. 919

    wow, talk about bloating your code unneccesarily. I suppose this is fine if you’re letting infants edit your code. Don’t get me wrong, I comment my code, but small, meaningingful comments before each section is sufficient. I also don’t think it’s wise to seperate out so many different style sheets – this will slow down both download and rendering time, especially if the files themselves are pretty big. I don’t even think it’s necessary to build a t.o.c either.

    I normally structure my css files as the items appear on the page. Starting at the top, with the basic body, then typography then the rest: side menu, main content then footer. It only ever takes me a second or two to find anything I’m looking for.

    I think keep it as simple as possible – try to have as few css files as possible – the more your page needs to call, the longer it takes to load and render.

  20. 970

    1. Use subversion, or version control of some kind. This really helps, as you don’t have to constantly update authorial info at the top of your css, you always know who has edited and why.

    2. If it’s possible make use of SASS – I believe someone already linked to the HAML project, but it’s worth re-iterating. SASS allows silent commenting, so you can comment all you like and it’ll be stripped out when the css is rendered. It also allows colour variables and has a whole other heap of features that make writing CSS a more pleasant experience.

    3. Yahoo have done a lot of testing on front-end rendering, and they claim there is a ‘noticeable’ hit on performance from using the @import rule to link to stylesheets. I don’t know for sure myself, I don’t tend to use it a great deal.

    4. As is mentioned in the ‘divide and conquer’ section, some people group their sections using a master stylesheet during development only, then they merge everything together when they put the stylesheet live, perform whatever other optimizations they want, and it’s this that they serve to the live site.

    Cheers for the article guys, interesting stuff, something any committed front-end developer needs to be thinking about really.

  21. 1021

    Your article was grand (the consistently HIGH quality of your content accounts for why your site is a permanent, static link on my page of recommended, client-side programming resources). I don’t unreservedly bless all the advice in the current article but deeply approve the majority.

    The MOST important issue accomplished herein is the raising of public awareness that standards MATTER MOST; doesn’t matter so much WHAT the standard is or from whence the standard springs – pick some and stick to ’em. Everyone who subscribes to the standards will benefit from the time-savings of the consistency of understanding that the standards supply. This is a VERY GOOD THING.

    The trade-off between request/response round-trips and modularization and decoupling of responsibilities MUST be assessed (as with all things web-ish, nay software-ish) locally. I prefer composite views (more page components being styled separately) and segregated responsibilities (e.g., typography and placement heed not the same masters) and having more *.css files. This can be short-punched on the server-side for Internet and local hardware performance.

    The embedding of inline commentary for documentation, I ever find a Best Practice; those who worry about the corresponding “file-bloat” may not have access to good “pre-compiler” resources. A good repository and set of “compaction” tools (or a Filter) can address this, but only if the shop can afford the effort/expense of debugging and supporting code that looks different in production than in dev/test.

    Short answer is there’s no short answer. The prime virtue of your presentation (besides some VERY good ideas) is to make people think more broadly and deeply about some very hard issues, i.e., stuff for which there is no closed, easy answer.

    My prime motivation is to reduce cost – developers are the MOST expensive variable of the equation. It’s why I read your stuff.

    You done good.

  22. 1072

    Thanks for all the tips here on your site. I’m new to CSS and I’m tweaking my blogs stylesheet more and more and these tips will definitely keep it more organized and less of a mess. Thanks.

  23. 1123

    A gorgeous code….

  24. 1174

    MAy I am wrong. But my Virus Software freaked out when I clicked on the link:”12 articles and tools for CSS Structuring and Optimizing ” from the recources area.

    Its says:
    Virus/Wurm – Malware
    http: //www.{gzip}

    So, be aware…

  25. 1225

    > “Ahhh, adding an extra indent to a line that has been recently changed sounds like a wonderful and easy way of simplifying later troublehsooting” [sic]

    Actually, relying on whitespace to tell you when something changed is a terrible idea. What does “recent” mean, exactly? Will you remember to go back and un-indent it? A much better idea is to use a source control system. Putting aside all of the other benefits of using an SCM, at the very least you should use one to tell you exactly what changed and when.

  26. 1276

    Thanks for the great resource. Very nice indeed.

  27. 1327

    Thanks, for a great post. I have learned so much from this (and your site) about CSS.

    Thanks Again

  28. 1378

    Jarod billingslea

    August 11, 2012 9:09 am

    I thought I was the only one that thought of indenting their CSS like the HTML syntax lol.

  29. 1429

    Thanks for the useful tips and recommendations!

  30. 1480

    Very good information! Only one thing I want to add is neatness of CSS code! It’s also very important! Here is example: improve CSS code.

  31. 1531

    Hey folks,

    I wrote a tool to generate table of contents for your CSS and JS. You can use the website or run it over your whole project using the command line.

    Hope you like it.


  32. 1582

    You should be using a css compressor for anything but the smallest of projects. This should have been mentioned in the article.

    The best thing about it is that you can comment to your hearts content!


↑ Back to top