CSS Code Visual Grouping Techniques

Anything large and complex that’s broken up into smaller parts or pieces is easier to digest than when it’s a whole. In CSS, arranging the different styles into compartments and sections makes it much easier to recognize and decipher at a glance, as opposed to scrolling through one big lump of ill-formed code. Below is a collection of basic and sensible coding practices (some you’ve probably seen before) that help create visual and logical groupings in your stylesheet. We start off with the obvious and popular, and then move on to some interesting formatting techniques.

A Word On Brackets

Because coders are exposed to different languages and conventions, it’s no surprise that there are some slight variations in the way we do things. One of these things is bracket placement. No matter what your preference is, each variation has it’s advantage, as described in each of the examples below:

/* Examples 1, 2: bandwidth-conscious, compact coding. */

selector { property-one: value; property-two: value; }

selector {
    property-one: value;
    property-two: value; }
/* Example 3: Newlined bottom bracket creates extra vertical
   space for visual separation from other rules. */

selector {
    property-one: value;
    property-two: value;
    }
/* Example 4: Newlined top bracket helps distinguish selector
   from declaration block. */

selector
{
    property-one: value;
    property-two: value;
}

For personal and historical reasons, I always go for the third example. Although, there are special occasions in which I use the first example, as you will see in action shortly.

Simple Indentations

A simple application of conventional formatting practices to your stylesheet will help produce code that’s easy to sift through. For example, style rule indentation (also known as the “9rules” technique) can help group a base selector and its descendants together:

ul {
    margin: 1em 0;
    padding: 0;
}
    ul li {
      list-style-type: square;  
    }
        ul ul li {
            font-style: italic;
            list-style-type: disc;
        }

When One-Liners Work

Putting the property-value pairs in the same line as the selector (and possibly defying coding conventions) can be a good thing when applying different values to the same property for related selectors, like when you want to apply different font-sizes to your headings:

#maincontent h1 { font-size: 3em; }
#maincontent h2 { font-size: 2.4em; }
#maincontent h3 { font-size: 1.8em; }
#maincontent h4 { font-size: 1.2em; }

Organize, Columnize

Take your one-liners further to accomodate selectors and properties with different character widths. Because code windows use monospace characters, you can use that old-skool word-processor space-bashing technique to perfectly line up your selectors, declaration blocks, and properties, as shown:

#main p.note     { color: #320; border:      #960 1px dashed; }
#main pre        { color: #333; border-left: #BBB 1px solid; }
#main blockquote {              border-left: #930 1px dotted; }

Sorting Properties

The declaration block itself can be organized by grouping the properties according to their function/usage and separating them with empty lines, like so:

img.thumbnail {
    position: relative;
    left: 12px;
    top: 25px;

    width: 400px;
    height: 300px;
}

Alternative: If you are more of an obsessive-compulsive coder (like this guy), it might suit you better to arrange your properties alphabetically. While losing the benefit of relational grouping, this method has the advantage of coding consistency and avoidance of duplicates. Because apple will always come before banana.

Taming Lengthy Selectors

When listing multiple selectors of similar descendance, or just long selectors in general, it’s a good idea to put them in separate lines for easier tracking and editting. To illustrate:

#sidebar #simplesearch input,
#sidebar #simplesearch label,
#sidebar #simplesearch select {
    font-family: "Lucida Grande", Verdana, Arial, sans-serif;
    font-size: 1.1em;
}

#masthead #quicksearch label,
#maincontent #advancedsearch label,
#sidebar #simplesearch label {
    color: #555;
    font-weight: bold;
}

A Word To The Wise…

Some of these formatting techniques require the use of additional spaces in your code, and we all know that spaces are characters, too. Whitespaces, tabs, and newlines can add to the bandwidth consumption of your website, especially for high-traffic pages. As with any practice, apply these methods with proper care and deliberation.

For further reading, check out:

31 Responses to “CSS Code Visual Grouping Techniques”


  • Thanks for sharing these. You know what I found recently – I saw that on Mozilla.org there is a TOC (Table of contents) in the CSS! See http://www.mozilla.org/css/base/content.css. I found the idea fascinating and adopted right away ;)

    As for the bandwidth – I don’t think it’s a big issue. Bandwidth is cheap these days, and on top of that the (external) CSS is cached on the first visit, so the impact is minimal. If it makes the stylesheet more organized and easier to understand – it will actually be costing less compared to the costs of maintenance.

  • another one with a TOC- http://exploding-boy.com/ :)

    dont let bandwidth make you skip out on the extra spacing and indenting in your css. you’ll thank yourself the next time you’re on a death march and trying to reuse styles..

  • I always go with #3 like yourself:

    selector {
    property-one: value;
    property-two: value;
    }

    I find that to be the best for when I have to go back and not have to dig through tons of junk like:

    selector { font-size: small; color: #333; line-height: 1.2; backround: #444 url(images/picture.jpg); text-transform: uppercase; }

    thats just too muddy.

    Thanks for the article. Good stuff!

  • I like the 4′th example :)
    good article.

  • I do one-liners, simple indentation and property groups. Columnize seems to be going a bit too far as you’re really wasting space for no apparent reason (I can’t see how that would help readability).

    Good article though,

    Nick

  • This is great, i’ve been seeing a lot of these CSS technique posts lately, but this is probably the most packed with great ideas and structure rules. Thanks for this, a good read for anyone doing any kind of CSS work.

  • Great article, the indentation idea makes so much sense.

    I Also like to make use of the commenting delimiters to draw lines between blocks of related code. So i’d surround my header, navigation, content, footer etc. rules with /*———*/

  • /me loves 1 line if there are few property… i’ll try the column mode…

  • I tend to string all my property-value pairs together on one or more lines while developing, and then put my style sheet through a formatter to get the one-pair-per-line layout when I need the readability. Conversely, you can develop in the expanded format and then put it through a formatter to create the most bandwidth-friendly style sheet just prior to publishing. And run it through the formatter the other way if you need the readability later.

  • Nick: In most instances, you probably wouldn’t get to use the columning technique, but in case you get the opportunity, it’s available. :)

    webzter: That formatter link was really helpful. Looks like the developers of CSSTidy and CDBurnerXP either know each other, or are one and the same.

  • I use a method a little bit, more condensed and with your method of simple indentations as this:

    #logograffikpix{
    position:absolute;
    top:190px; left:54px;
    width:80px; height:9px;
    color:#f60;
    padding:10px 4px;
    }

  • There’s a typo in the first example.

    property-two; value;

    should be replaced with

    property-two: value;

  • Jos: Thanks for the correction. You have eagle eyes. :)

  • does anyone know any CSS formating tools?

  • Nat: Apparently, this isn’t the only article of mine he’s so lovingly copied. He did remove it promptly after I told him to take it down. I guess that’s the end of that.

  • Formatting style in everything but Python is tightly bound to individual preference. I really can’t connect the explanations given with the examples presented. As long as you’re consistent and can read it and it validates who cares. This here is borderline OCD. Perhaps you’d like to use css to format your css…

  • Bjorn:

    Formatting style in everything but Python is tightly bound to individual preference.

    Formatting shouldn’t benefit just you as the creator of the stylesheet. It should also enable other coders (in a multi-developer environment, or when the project is passed off to someone else, for examples) to easily read what has already been written. Individual preference rarely exists in situations other than one-man design-development teams.

    This here is borderline OCD.

    “Borderline” is understating it. :)

    Perhaps you’d like to use css to format your css…

    *Sigh* If that were to happen, i’d be a happy camper. :D

  • Great reminding and in some cases (as the indentation part) refreshing article. Cheers!

  • Does anyone know of an application that will format scruffy css code/source???

    Any of the format styles above would be better than some of the mess i have ended up with after cuting and pasting from various sources over time.

  • Jonnyleaf: Check out what webzter wrote; he has a link to a nice online CSS formatting tool that’s based on CSSTidy.

  • I am glad I found your entry from this. I am learning CSS and it’s great to read posts like these. It is encouraging me to learn more :)

  • Hey, did you just call me obsessive-compulsive? ;)

    Yes, I use a variant of #3 (I keep the closing curly at line base too to indicate it closes a block started at same indent), and I sort my definitions alphabetically 95% of the time. Purism leading to clarity.

  • Thank you so much for sharing this awesome info. I will book mark this page for future reference when I’m knee deep in code.

  • Interesting, indeed.

  • Hi am working on a CSS Validator for web pages.
    I need to seperate CSS from web pages. Please anybody knows about a C or C++ code regarding this…?
    Please help me out..

  • Thank you so much for sharing this great article.

  • Thanks for the great article! II like using example #3 as well, I find it much easier to scan quickly and make error corrections faster. Keep up the great work!

  • Great article. I tend to use your example #4 (or a close derivative of it) as it is the easiest for me to scan through quickly.

  • Thanks for sharing. Great article.

Comments are currently closed.