In 2009, at An Event Apart in Chicago, I listened as Nicole Sullivan laid out the most compelling way to write CSS I had ever heard. It was called Object Oriented CSS. That talk alone was worth my AEA ticket, the plane ticket, hotel and everything else. It’s the one thing I would tell any designer or front-end developer that they should change about the way they write CSS. The primary takeaways for me were:

  1. never reference elements by ID, leave those for JavaScript;
  2. never specify elements; and
  3. use multiple classes to style elements.

The first is straight-forward, if you style an ID it’s a dead end, you can’t reuse it. By only referencing classes, you always have the ability to reuse styles; and the only specificity issues you need to worry about are where in the cascade they fall.

The second is related to the first, when you reference a specific type of element you are creating another needless dead end. Granted it’s more flexible than referencing an ID, but it’s still unnecessary, and creates specificity issues that in my experience lead to bloated code down the road. You could extrapolate various scenarios on why you shouldn’t reference elements but the most compelling to me is you just don’t need to.1

The third is where the “object oriented” part of it comes into play. Let’s say you have one sub header (.subhead) in your text that’s blue, italic, and all caps and another (.minor-subhead) that’s gray and italic.

You could write it like this:

And the corresponding markup would be something like this:

But we can do better. Let’s change the CSS to this:

And then our markup changes:2

Ah, much better.

Of note

No matter the best of intentions sometimes life gets in the way and you end up with something like #main h3.subhead { color: #f0f !important; }. Don’t let it trip you up, it happens. If you view the CSS for this site you’ll likely see some things that make you cringe. What’s most important is that you take time to go back and clean up the messes you can and don’t sweat the ones you can’t.

  1. This gets tricky for elements like the p tag. Nicole Sullivan advocated in this case using classes that match the element’s name (e.g. <p class=”p”>) and then referencing them in the CSS by class like the rest. I would agree with this approach, however unless you can easily dive into the cogs of your content management system it’s not always practical.
  2. The order in which you reference the classes in the markup attribute has no bearing on specificity. That all happens in the CSS file. My personal preference is to start with the most specific class and end with the most generic.