Improving Code Readability With CSS Styleguides

Advertisement

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.

/*------------------------------------------------------------------
[Typography]

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:

body,
	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 */
}

Conclusion

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

Footnotes

  1. 1 http://www.smashingmagazine.com/2007/05/10/70-expert-ideas-for-better-css-coding/
  2. 2 http://www.smashingmagazine.com/2007/07/12/time-savers-code-beautifier-and-formatter/
  3. 3 http://www.smashingmagazine.com/2006/09/02/list-of-css-tools/
  4. 4 http://meyerweb.com/eric/thoughts/2007/09/07/diagnostic-styling/
  5. 5 http://24ways.org/2006/faster-development-with-css-constants
  6. 6 http://css-tricks.com/indent-css-changes-you-are-unsure-about/
  7. 7 http://www.louddog.com/bloggity/2008/03/css-best-practices.php
  8. 8 http://css-tricks.com/indent-css-changes-you-are-unsure-about/
  9. 9 http://woork.blogspot.com/2008/03/write-well-structured-css-file-without.html
  10. 10 http://woork.blogspot.com/2008/01/optimize-your-css-files-to-improve-code.html
  11. 11 http://www.onyx-design.net/weblog2/css/12-articles-and-tools-for-css-structuring-and-optimising/
  12. 12 http://www.smashingmagazine.com/2007/05/10/70-expert-ideas-for-better-css-coding/
  13. 13 http://css-tricks.com/videos/css-tricks-video-8.php

↑ Back to topShare on Twitter

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 and loves solving complex problems in large companies. Get in touch.

Advertising
  1. 1

    Thnx!

    -4
  2. 2

    Great work as always, some really helpful tips! Thanks Smashing!

    -1
  3. 3

    All well and good if you have a script to remove those contents prior to serving it to a visitor. Otherwise your maintainable CSS has a good chance at slowing down your visitors’ experiences with excessive file-sizes comprised of primarily comments and whitespace.

    I’m not advocating a lack of comments, but pointing out that this solution only works well if you can dynamically strip comments and spaces. Only then do you get the benefit of readable, maintainable, and tiny code.

    Same thing goes for external javascript.

    0
  4. 4

    I’m all for keeping notes, but like Arthur Lawry said these css comments can add size if you’re not careful. I think for smaller websites it’s not an issue though and come to think of it, I’d rather loose 1/2 a second of load time than loosing my brain trying to figure out what I did two years ago. :)

    0
  5. 5

    Paul Armstrong

    May 2, 2008 7:11 am

    Using the @import rule is likely to give your new visitors the “FOUC” bug (Flash Of Unstyled Content), where your html page renders without any CSS styles because the @import stylesheets get loaded after the page.

    I wouldn’t recommend using that method.

    4
  6. 6

    I agree with Paul Armstrong. @import isn’t always the best of ideas.

    0
  7. 7

    Great suggestion!

    0
  8. 8

    The table of contents is a good approach to index what’s on a CSS page. I’m curious how this could be used to manage several CSS files?

    One thing to consider is the file size. I’ve been trying to optimize by reducing lines, leaving out comments and such but putting them in where it’s really needed.

    These are good practices though to consider if you have developers and designers working on a CSS page.

    0
  9. 9

    Michael Thompson

    May 2, 2008 7:49 am

    “Some developers use a more interesting approach and group properties in an alphabetical order. In this context it’s important to mention that alphabetizing CSS properties may lead to some problems in some browsers.

    Wrong — alphabetizing your attributes won’t cause any problems.

    0
  10. 10

    Acctually it could, if your CSS inherit on one another without using “!important”.

    As for the file size, you shouldn’t bother with that, the version that you are sending to the client should be minified with something like YUI Compressor. The commented version is for your development, and for tweaking stuff unitll you are ready to let the new style sheet to the clients.

    0
  11. 11

    There’s another reason to go easy on the comments, at least for CSS that’s in the head of an (x)html doc inside style tags. Long visual dividers like the ones above, made of hyphens (minus signs) will choke the W3C validator (using plus signs, underscores, periods etc. won’t).

    0
  12. 12

    Ahhh, adding an extra indent to a line that has been recently changed sounds like a wonderful and easy way of simplifying later troublehsooting… sw-ee-ee-ee-ttt…

    0
  13. 13

    Utilizing these methods makes re-creating a stylesheet much more efficient.

    Not only does it allow for quicker production but also means you don’t leave anything out. I have a blank stylesheet with the second styled TOC, including all typography etc. I’ve gone from days of coding to hours to create the basics. Thanks Smashing!

    0
  14. 14

    The biggest issue with using @import is that it causes extra http requests to the server and slows down site performance. Best practice is to house all your css in 1 file, it takes less time to load 1 large file than 8 small ones (file size + request time)

    0
  15. 15

    wow, will make use of it in my next project…

    0
  16. 16

    I use Sass to organize my stylesheets. Best of all, it allows for variables so I only have to define my colors once.

    0
  17. 17

    Instead of using @imports, I use php to include groups into a master stylesheet. This prevents extra http-requests (and FOUC).

    0
  18. 18

    I don’t agree with everything – but there are some good tips here. I will add some to my own

    0
  19. 19

    There are some great tips here – almost all of which I follow.

    Sadly, in my experience, these kinds of things are just not kept upwhen other people in the team edit the CSS file.

    0
  20. 20

    This article is amazing. This is what I will be using from here on out!

    0
  21. 21

    @Lica

    *lose

    *losing

    0
  22. 22

    Excellent tips. Thank you!

    0
  23. 23

    Most of this tips are not OK in a production process. These tips are used in the development process, because on the final release you will want to reduce the file size.

    0
  24. 24

    Jeff MacCharles

    May 2, 2008 4:15 pm

    I agree, comments are nice; but can get out of control quickly and are timely. Sometimes what i do is i will create a text file that uses the commenting guidelines and aplly it for each stylesheet. This way i can keep my .css file small but still have a detailed reference for the future.

    0
  25. 25

    Fabulous timing of this post! I was just thinking this morning that I needed a more consistent way of writing my css. I am not a fan of the css libraries, so doing it myself is my favorite option.

    Thanks for this post!

    0
  26. 26

    I hand code everything so I tend to comment a lot in my PHP scripts. For CSS I tend to write a small .txt file that houses the layouts and other general notes. Basically a ‘read_me’ file in my CSS directory. That way the browser doesn’t have to load it but it’s there for development and maintenance.

    Also, I tend to order my CSS in the same fashion I program it. First I do positioning/float styles, followed by dimensions/margin/padding styles, then text styles. A kind of ‘work from the outside – in’ approach.

    Works for me anyway and that’s the most important thing for organizing anything you do!

    0
  27. 27

    Mithun Sreedharan

    May 2, 2008 8:52 pm

    Good stuff here, good comments also. First time I feel comments are better than the post, aw! sorry, better than the code!
    Well, I’m a fan of alphabetizing CSS properties.

    0
  28. 28

    Sandeep Sharma

    May 2, 2008 9:42 pm

    Great suggestion! Thank you.

    -1
  29. 29

    Simple but effective and powerful when it comes to cleaning up a rat’s nest of CSS. Thanks!

    0
  30. 30

    I love this post,

    -1
  31. 31

    Good ideas!
    You should share your ideas with the guys from the project CSSDoc:
    http://cssdoc.net/
    It’s an approach to comment CSS-documents the same way like you use for Java- or PHPdoc.

    In times of Web >= 2 CSS becomes more and more powerful and it seems that coding-wise it is still a real mess.
    Therefore I plead for a css-nationally coding guide/concept :-)
    Cheers.
    QT

    0
  32. 32

    Nout van Deijck - Blog

    May 3, 2008 1:10 am

    Thanks very much!
    I’m going to manage my stylesheets better now!

    -1
  33. 33

    Good article and comments,

    these thoughts are really needed, even an averagely maintained C++ project is more readable than a professional (x)html site’s html, css, php and javascript mash-up.

    good points, QT. i think that the whole html concept itself is the wrong way. all its incompatible extensions, confusing styling techniques and complex workarounds are a big mess IMO.

    all this could be much easier and less error-prone…

    0
  34. 34

    1. It’s always good do divide the code, and import other css, this results in speed eventually
    2. It’s bad to define table of contents and to define colors withing the /* */ in CSS you end up with a css that will load TOMORROW (enourmous size) … Last time i cheeked the smashingmagazine css it had more then 50 kb and this is not good. You guys wrote a novel withing /* */ it’s always nice to keep it simple and perfect. Not everybody has super internet connections like we do.

    You guys should correct the article. If you are going to make a table of contents do it on paper but keep the css as tiny as simple as possible.

    0
  35. 35

    webpixelkonsum

    May 3, 2008 7:29 am

    Thank you for this great article to improve my own css – style.

    Ralph

    -1
  36. 36

    Some tips are fine but mostly bad.

    1. Document your CSS structures/color schemes on a separate CSS file.
    2. Don’t use nested @import “” inside a CSS file. Slows down your loading speed.
    3. In Article it said uses one liner moderately? I don’t get it… many times you’ll have more than 3 attributes….your css file is going to be so hard to read

    0
  37. 37

    If you are working in a team have a lot of comments is very helpful in development phase. Just make sure to remove them when in production. ;-)

    0
  38. 38

    I’m a brand new Web Designer for a fairly big company and I’ve been giving the task to managing the whole design and css building. These article is great. Thank you so much.

    0
  39. 39

    Isaac Castillo

    May 3, 2008 7:52 pm

    Great post guys!

    -1
  40. 40

    thx for the tips guys.

    -1
  41. 41

    Thank you, this is helps me a lot!!

    -1
  42. 42

    Kilian Valkhof

    May 4, 2008 4:24 am

    There are some neat ideas in this article!

    Though, like Michael pointed out there is an error in it: Alphabetising properties (the stuff between {} )will not have any effect on rendering. Alphabetising selectors (The stuff in front of {} ) however will have major effects on your rendering,

    Given two selectors with exactly the same weight (say, #content p and #main p, the lastly declared selector will always be applied. Also note that this has nothing to do with cross browser stuff, all browsers handle this in the same way.

    0
  43. 43

    I like kicking it old school all the time, so I don’t take to new ideas and fads very easily. However, your suggestions here make excellent sense and I keep thinking why I didn’t consider them sooner.

    0
  44. 44

    Great post! It is a good suggestion. Thanks SM! m/

    -1
  45. 45

    Vitaly Friedman & Sven Lennartz

    May 4, 2008 8:46 am

    @all: Thank you. The article was updated.

    0
  46. 46

    v neat idea! thanks alot SM!! :D

    -1
  47. 47

    Just as I discovered this technique when I was editing the theme template on Prestashop few days before!

    0
  48. 48

    Please, delete such stupid reply as “wow~ so awsome” or “thx!”, “you help me a lot”…

    -1
  49. 49

    Enggal Mandiri

    May 4, 2008 10:07 pm

    Nice post! :)

    Although all of those techniques above are already implemented by me in most of my projects since half-a-year ago, I was hoping that those techniques can improve many web-programmers for their CSS writing style. So someday, it would be happier for someone who want to learn CSS from some websites because of the readability-code.. :)

    Obviously, I’m gonna send this smashing article to my friends too! :D

    0
  50. 50

    Very nice. Definitely gave me something to think about. I am busy creating the layout for a new project these days, and I’ll definitely be using some of these tips.

    0
  51. 51

    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.

    0
  52. 52

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

    0
  53. 53

    Karol Adamczyk

    May 5, 2008 11:07 am

    Or simply use firebug…

    0
  54. 54

    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

    0
  55. 55

    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!

    0
  56. 56

    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.

    0
  57. 57

    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

    0
  58. 58

    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

    0
  59. 59

    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.

    0
  60. 60

    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.

    0
  61. 61

    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: http://jadeohlhauser.com/strip/

    0
  62. 62

    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.

    0
  63. 63

    thx.. this is really helpful

    -1
  64. 64

    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,
    Edgar

    0
  65. 65

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

    0
  66. 66

    /*------------------------------------------------------------------
    [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.

    0
  67. 67

    Thanks for help.

    0
  68. 68

    Jérôme Jaglale

    May 22, 2008 3:31 pm

    If you have a mac, use CSSEdit:
    http://macrabbit.com/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

    0
  69. 69

    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.

    0
  70. 70

    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.

    0
  71. 71

    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.

    1
  72. 72

    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.

    0
  73. 73

    A gorgeous code….

    0
  74. 74

    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:
    TML:Iframe-inf
    Virus/Wurm – Malware
    http: //www. designfloat.com/evb/button.php{gzip}

    So, be aware…

    0
  75. 75

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

    0
  76. 76

    Thanks for the great resource. Very nice indeed.

    0
  77. 77

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

    Thanks Again

    0
  78. 78

    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.

    0
  79. 79

    Thanks for the useful tips and recommendations!

    0
  80. 80

    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.

    0
  81. 81

    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.

    http://tocgen.net
    https://github.com/redaxmedia/tocgen

    Hope you like it.

    Regards

    0
  82. 82

    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!

    0

↑ Back to top