This week’s question comes from Jitendra Vyas.
What is your opinion about OOCSS approach? Will it not litter our HTML code with lots of classes?
Sherpa Allison Wagner answers:
Yay! I love this question because it touches on a very common misconception about Object Oriented CSS.
The answer is no. OOCSS does not mean you have to degrade your markup with tons of non-semantic classes that pull in single properties. Consider this example:
<div class="blue rounded cushion highlight shadow">
The classes referenced each declare a single property:
.blue { border: 1px solid blue; }
.rounded { border-radius: 5px; }
.cushion { padding: 40px; }
.highlight { background: yellow; }
.shadow { box-shadow: 0px 2px 3px 1px #000; }
This is not OOCSS.
What Is OOCSS?
OOCSS simply encourages you to think about your design as a series of repeated patterns, such as border and button styles, font declarations, etc. Once you identify your basic design elements, you turn them into “objects” in your CSS in the form of classes. In the following example, .module
and .highlight
are both objects:
<div class="highlight module">
.module { border-radius: 5px; padding: 40px; box-shadow: 0px 2px 3px 1px #000; }
.highlight { border: 1px solid blue; background: yellow; }
Benefits of OOCSS
In addition to identifying and abstracting patterns into classes, OOCSS helps keep your selector strings short (personally, I try to stay under three declarations in any given selector). You also avoid overly specific selectors, using the cascade to your advantage instead of needing !important
, IDs or additional selectors. And finally, your objects are portable enough that you can drop them anywhere in your templates and they maintain their core integrity.
Preprocessors: Sass
Worth noting, I’ve been using Sass to write CSS for a little bit now. Favoring the OOCSS approach, Sass solves the “littered markup” problem elegantly. Instead of adding multiple classes to your markup, you bundle classes with @extends
. Revisiting the example above with Sass looks like:
<div class="featured-callout">
.module { border-radius: 5px; padding: 40px; box-shadow: 0px 2px 3px 1px #000; }
.highlight { border: 1px solid blue; background: yellow; }
.featured-callout { @extend module; @extend highlight; }
Check out Brad Frost’s notes on Nicole Sullivan’s Smashing Conf talk all about Preprocessors and OOCSS for more on this topic.
Share Your Thoughts
Please Log in or Sign up to share your thoughts.