Josh Clayton

husband, father, programmer, hophead

Structuring CSS Intelligently

Signal vs Noise just did a writeup about CSS, the cascade, and some of their latest and greatest styling notes. Although some of the advice is sound (SCSS is great), recommending that the CSS explicitly mimic the DOM structure is a horrible mistake.

As Jason points out, one great thing about CSS (and also the part that can shoot you in the foot) is the fact that styles cascade. This (apart from the box model) is, in my opinion, one of the hardest things to grasp about CSS. If you don’t understand how selectors work, how to manage specificity, and how to maintain a structured set of CSS rules, it becomes a giant pain to manage a relatively small site.

In the end, I think the key here is to use modularity to your advantage. Programmers do this all the time - we break up various pieces of code that behave the same and abstract them out into a single reusable piece that can be reused throughout the application. Markup (and subsequently CSS) can be thought of in a similar manner. If you have a chunk of content that follows a certain set of guidelines (content with a header, possible sub-header, and one or many paragraphs), and that style is used in a couple of different spots (maybe with an unordered list instead of a paragraph), start to recognize a structure and build styles on reusable containers of code.

Suggesting that the CSS mimic the markup is virtually as bad as inlining the CSS. Instead, use a semantic class name describing the content and style that one chunk of markup in the manner you’d like.

I personally try and stick with simple selectors (one class name, maybe two at the most) and never go more than four or five levels deep. This helps keep the selectors themselves from getting way too long (html body div.container header#page-header h1.welcome, anyone?) and makes things much easier to maintain.