Managing CSS: part 1, Factoring

By: on September 13, 2006

In these days of semantic markup, liquid three column layouts and image replacement it’s quite evident that using CSS is just not as simple as it promises to be. There’s not only the flow and box models to internalise, but the numerous quirks in how browsers implement them, and the constraints imposed by accessibility guidelines, and—well, special cases galore. As usual the solution is care, attention, and better tools.

Grouping rules

To start, there is the matter of how to arrange CSS code: One reason why CSS can be trouble to maintain is that there’s no obvious best factoring of rules. Do you clump like properties together under a single selector

h1, h2, h3, div.title  {color: #f3c;}

on the basis that there’s then one place to change that property of these related elements; or, group like selectors

h1 { color: #f3c; font-size: largest; font-weight: bold; }

so that the entire style of a particular set of related elements can be changed at once?

There is at least one program that will automagically group rules for you, but it does it dumbly, collecting rules by common properties, and as it’s been pointed out, that’s not always what you want.

The real answer is that it depends on for what each property is intended. If a property is part of the overall theme, it should be in one place. Colours often fall into this category, as do fonts. If the property is a consequence of some extra semantics you’re asserting with your selector, it belongs with all the other such properties under one rule. For example, if I create a distinction between hyperlinks to elsewhere in my site and hyperlinks leading away from my site by using the class external, I would put all the properties related to external links in one rule.

These rules may have related selectors:

// Thematic property --- this colour is part of my colour scheme
h1, h2, h3, div.title {color: #0f0;}

// Semantic properties -- I'm asserting a set of things that are titles
*.title {
  margin-left: 32px;
  background-image: url('images/title-marker.gif');
  background-repeat: no-repeat;

(Note to CSS standards authors: some extra sugar for selectors would be helpful, like distributing combinators over parentheses; for example thead (th, td) as shorthand for thead th, thead td)

Cascade Simply, Stupid

The typical practice is to put hooks in the HTML upon which to hang styles. An id attribute can be used for unique (per page) elements, and the class attribute can be used to create arbitrary sets of elements. This coupling between the HTML and the CSS introduces a maintenance burden, since when the HTML changes the CSS must change, and vice versa.

There’s many ways to select a particular element, and there’s many ways of getting a style to apply to an element. A question Mark Bernstein poses is how do you make sure your style applies to precisely the right set of elements, now and forever?

We want to minimise three things: the knock-on effect of changing the CSS or the HTML, the possibility of unintended matches, and dependencies between rules. We can go a long way with both by keeping selectors simple and predictable.

Use either very general selectors with thematic properties (“set all body text to green”), or very specific selectors (“the element with this ID has a blue background”). This makes it easier to predict which elements will be affected by a rule, and reduces the chance that undesired properties will be inherited.

If you use relative units on elements that can be nested, you can end up with effects like shrinking text. This applies not only to single rules, but to combinations of rules: { font-size: 0.8em; }
// OK, since it won't be nested

fieldset#login { font-size: 0.9em; }
// but what if we put a in that fieldset?

To avoid this situation, keep relative units away from generic containers. Let paragraphs default to whatever the body text size is, and adjust only for non-nesting elements.

Use selector connectors (descendant, child, sibling) very sparingly: they appear specific without being very predictable. Qualify sub-selectors with a class, or better an ID, to help avoid matching undesired elements.


Refactoring is the process of removing duplication and other bad smells from code. We can do the same for CSS.

What are the bad smells?

Sets of repeated properties in several rules often signal that there’s a common class to be extracted. You have to be careful though: it may be coincidence. A rule of thumb is that if you can consider the set of selected elements semantically alike, then you can replace the rules with a class. The semantic similarity means there’s a reasonable chance that the class, and the elements to which it it is attributed, aren’t going to change.

Class names or IDs that mention styles, for example .redBox, suggest that thematic properties are being mixed with semantic properties (or possibly that you were running short on imagination that day). Move the thematic properties into their own rule and think of a new name that reflects why you’re saying the elements with this class are different to other elements; e.g., .warning. Long chains of combined selectors, for example body#about-page div.sidebar p a {...} may mean you’re trying too hard to narrow a selection — use a class or ID further down the chain to simplify the rule and make the selection clearer: p.about-page-links a {...}.

The hypothetical refactoring browser

What’s really needed is a refactoring browser. Not only would this browser let you view and edit CSS and HTML (and HTML-like code) side-by-side, it would understand how CSS applies to HTML, so you could

– see which rules apply to an element
– see which elements a selector matches
– see how the effective properties of an element are derived (inherited properties, relative units)
– see dependencies between rules (which rules will cascade)

It would also offer refactoring transformations:

– move common properties into another rule
– merge similar rules (and put the remainder into another rule)
– move a class into or out of a nested element
– collapse (redundantly) cascading rules

By definition, refactoring transformations should not alter the observable output of the code; however, you will also want to know when something you’ve done has failed to preserve that, so the refactoring browser should tell you.

Xylescope comes very close—it does a excellent job of showing you both which rules apply to an element and to which elements a rule applies, and has some handy visualisations of CSS properties (especially the box model). Sadly it doesn’t have a stellar editing facility, or any refactoring, but we can hope that culturedcode are planning to extend it.

Care and attention

While tools go an awfully long way, the most important thing is to give CSS your care and attention. Don’t let it get out of hand, by constantly refactoring; update the CSS when you update the HTML to remove unneeded rules; and confirm that each new rule does what you think it does. This last activity is the essence of testing, which I’ll talk about next time.


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>