DRY CSS

When I first thought of writing this post, my ideas were more about describing a good CSS organization and using reusable stylesheets. There are two tips in this area that I still recommend:

An element can have multiple classes: It’s a pretty simple idea, but isolate out layout styles and presentation styles. Even fonts and coloring. Make reusable classes as much as possible. A design like this rocks, esp. if it includes a small description of the classes used at the top of the .css file. At any point you feel an urge to create a new class, resist the urge and try to recreate the functionality using already existing ones. Break older classes further if you have to.

For e.g.:

.warn {
  color: red;
}

.top {
  position: absolute;
  top: 5px;
}

And this html:

<p class="warn top">You cannot do that, it'll wreck havoc!</p>

… is way better than combining those tasks. Why? Because you can reuse those classes.

Keep your page-specific CSS structured by an ID on the body: Again, a pretty simple idea, the <body> tag can take an ID that can be an indicator of the page name. Use that to create special styles for that page alone.

Example: you want the warning on product pages to appear in blue instead of the usual red, and you want more padding on top:

#product-page .warn {
  color: blue;
}

#product-page .top {
  position: absolute;
  top: 10px;
}

with this HTML:

...
<body id="product-page">
...
<p class="warn top">You cannot do that, it'll wreck havoc!</p>
...
</body>

The advantage is that you don’t hack the CSS or add more styles. It just works.

I have more CSS organization tips, but the above two have worked wonders in 90% of the projects I’ve been involved in. Let’s move on to using tools to write better CSS.

Use a CSS generator: In the Ruby/Rails world where I mostly live nowadays, there’s an excellent plugin called cssdryer. Using this, the CSS above becomes much cleaner:

#product-page {
  .warn {
    color: blue;
  }

  .top {
    position: absolute;
    top: 10px;
  }
}

… which is lovely. Finally, nested tags! And variables, and all the power of ruby! [There’s also Sass]

If you are not in ruby land, use a CSS pre-processor. This article uses the m4 macro processor to generate DRY CSS.

Now, here’s one more lovely tip. Use a CSS framework. The most appealing one (altho in beta) is blueprint, since it only does a sweet grid system and good typography. Yahoo’s Grids seem bloated.