“Describing in the Browser” with OOCSS-Inspired Microclasses
Over the course of the past year, the way I approach CSS has fundamentally changed for two reasons.
The first reason is that I now use SASS. I could drone on for days about how amazing it is, but I think enough blog posts have been written on that topic. (Having said that, please note that everything I am going to discuss here is a zillion times more awesome and powerful when combined with a preprocessor like SASS or LESS.)
What I want to talk about instead is the second reason I’m writing styles and markup a lot differently than I was 12 months ago: a little toolbox of Object-Oriented CSS–inspired microclasses that allow me to code in a way I like to call “Describing in the Browser”.
Ugh. Microclass? Describing in the Browser? That sounds pretentious and, well, hard. Au contraire, mon frère. This is one of my favorite and most frequently used microclasses:
.pad-box { padding: 20px; } |
Have I blown your mind yet?! No? Try this sucker on for size:
.content-box { margin: 20px 0; } |
No love? OK, time to bring out the big CSS3 guns. BLAM!
.corner-box { border-radius: 4px; } .shadow-box { box-shadow: 0 5px 5px rgba(0,0,0,0.3); } |
Not exactly cutting-edge stuff, huh? In fact, if you’d told me a year ago I’d be writing a blog post advocating the CSS you just read, I’d have slapped your new iPhone 4S right out of your hands before you’d even had a chance to chat with Siri. Devoting a whole class to a single declaration? What? Why? That looks like some wack Dreamweaver-generated code from 2005 (anyone else remember style-261 {color:red}?).
And me-from-a-year-ago would have been about right: a microclass in and of itself is nothing to write home about. It’s just a tiny, generic class that does one presentational “thing”. However, it does that one thing really well, and true to the principles of OOCSS, it does it anywhere. No matter where — and to what element — you apply .pad-box, you’re going to reliably get your 20px of padding. However, the real magic of microclasses happens when you combine them. Here’s some markup I wrote today:
This is where things finally start getting cool. For one thing, I didn’t have to create any new classes to style this div: All I had to do was combine six existing microclasses to get where I wanted to go visually. (While working on Kunvay, for example, I found that it wasn’t uncommon to implement an entire page of content with a fairly complex layout, without needing to write a single line of new CSS.)

So while I’m rocking what some people call “class-itis” (a.k.a., a sh$t ton of classes) in my markup, my CSS is lighter and more maintainable – and that’s a tradeoff I’ll make any day.
Describing in the Browser
So that’s great, but what I’ve really fallen in love with (and bear with me while I get a little pretentious) is the way that microclasses allow you to “describe” the visual presentation of an element while writing markup in a way that can feel as natural as composing a sentence in your native language. Compare the visual/design requirements for the above div with the markup itself:
A rounded-corner box, filled with the client’s signature dark orange, with a little bit of padding, a drop shadow, and white text; and there’s going to be stuff before and after this content, so also add some margin to the top and bottom.
See the symmetry there? I’ve found that with a library of these small, generic classes at my disposal, writing markup has transformed from a chore into something expressive and creative: As we all know, every block-level html element is essentially a blank rectangular box; once I’ve set up my microclasses for an app, I’m able to easily and intuitively describe what I want each box on my page to look like and how I want them laid out.
DRY as a Bone
A welcome side effect of this technique is a new-found level of DRY-ness in my code. I used to do stuff like this:
Well, hmmm, it seems like most forms need a little space around them, so I’ll stick this in my main styles …
form { margin: 20px 0; } |
And then invariably there’ll be a situation where a form doesn’t need that space around it — usually because its container element already has some padding or margin; so I’ll have to write something like this:
.my-container form { margin: 0; } |
But then, of course, the client introduces a second form within that same .my-container element, and in this case, the second form does need some space above — but not below — it. So I’d hate myself and maybe give the stupid form an ID to overwrite all the things, like this:
#username-form { margin: 20px 0 0; } |
These days, I simply add my trusty .content-box and .last-box microclasses to any block-level element I want to separate out with some top-only vertical white space:
.content-box { margin: 20px 0; } .last-box { margin-bottom: 0; } |
<!-- the first form in our example above --> |
<!-- the second form --> |
Beyond the original microclasses, I’ve not had to write any CSS to override the element’s default styles. Instead, I simply describe right in the markup how I want each form to behave visually: content-box adds the margin we need, and .last-box erases the bottom margin.
And if, say, the client or I decide that second form’s not quite “popping” enough, I’d just do something like this:
Translated into English: A form with whitespace at the top but not the bottom, with a border, rounded corners, a light gray background, a subtle bevel effect and some padding. Total lines of new CSS? Zero.
Consistency: the hobgoblin of little minds (and little classes)
Using microclasses automatically enforces a consistent look and feel because elements all pull a particular visual property from a single class. When I start a project and tweak the values for my .shadow-box class, for example, I’m making an (easily editable) decision about what I want an outset drop shadow to look like throughout the app. Likewise, when I assign a value to the margin in my .content-box class, I’m deciding how much white space should separate all the stuff (divs, forms, sections, whatever) in my app.
“But, wah!”, I hear you saying. “I don’t want to use the same outset drop shadow and margin everywhere on my site. I wanna be creative!” Well, I do, too, sometimes. To accommodate situations like these, I’ve developed a “micro > mini > [normal] > mega” convention in my microclasses. Sometimes I need the micro-, -mini and -mega classes; sometimes I don’t.
.content-box { margin: 20px 0; } .content-box-micro { margin: 10px 0; } .content-box-mini { margin: 10px 0; } .content-box-mega { 30px 0; } .shadow-box { box-shadow: 0 5px 5px rgba(0,0,0,0.5); } .shadow-box-mini { box-shadow: 0 2px 2px rgba(0,0,0,0.5); } .shadow-box-mega { box-shadow: 0 10px 10px rgba(0,0,0,0.5); } |
Still not creatively satisfied? Well, IMHO if you’re using more than three varieties of outset drop shadow, you’re probably doing it wrong. Haters gonna hate.
Give it a try
I’ve prepared a demo page that uses some of my favorite microclasses. Let me know if you find them useful. As I said at the beginning of this post, adding a precompiler like SASS or LESS to the equation only makes things 100 times cooler. (These days most of my microclasses are tied to SASS variables or mixins.) For the purposes of this article, however, I wanted to keep the focus on microclasses and how using them to “describe in the browser” has helped me work faster and produce lighter, more scalable CSS..


Why I love “describing in the browser” with OOCSS-Inspired Microclasses | My Daily Feeds
Oct 31, 2012 @ 10:54:24
[...] Hacker News http://blog.12spokes.com/web-design-development/describing-in-the-browser-with-oocss-inspired-microc… This entry was posted in Uncategorized by admin. Bookmark the [...]
Oct 31, 2012 @ 11:06:30
I understand what you’re trying to gain in terms of maintainable CSS but can you at least address the elephant in the room?
CSS is meant to be about separating presentation from content (and structure). This approach massively breaks with that.
Have you reached an informed decision on the matter in terms of costs vs benefits? Or is it not something you’ve really considered?
Oct 31, 2012 @ 11:17:14
I’m going to try something similar with mixins. So rather than filling my HTML with classes, I’ll keep them nice and descriptive, and instead have rules like
button
+pad-box
+brand-bg
Regreso al pasado | Dupermag
Oct 31, 2012 @ 11:34:20
[...] favor lean este post sobre microclases en css para que vean la forma más estúpida posible de crear sitios web con html y css. [...]
Oct 31, 2012 @ 11:34:25
@AlexHeeton I like that approach rather than “class-itis” approach in the article
Oct 31, 2012 @ 11:40:49
Continuing on the concern Andy Baker brings up…
I like the idea of the narrowly focused style definitions but (and it may just be the way you wrote out the examples) it looks like you are not peppering your HTML with all this class = ” …”
Maybe its just because you wanted to emphasis how can build a fully defined style from a series of narrow class definitions.
But in real code you should pull out all the style injects from the HTML and use more HTML hierarchy selectors which then specify the micro-classes to apply (via mixins)
Oct 31, 2012 @ 11:59:11
I agree with the first commenter – this deviates from CSS’ true nature, and also causes needless DOM bloat.
However, I do use this approach for certain UI elements, especially things like buttons, menus, etc.
Oct 31, 2012 @ 12:22:52
after doing this for a while, you’ll figure out that most apps will collapse into a few major classes, and that the really useful “microclasses” are for layout. then you’ll also start hearing that solutions like less and sass solve this in a different, more widely accepted way. the best “microclass” IMO is “.bar” which goes:
.bar > div { float: left;}
Oct 31, 2012 @ 13:31:39
I think you missed the point of object oriented css. Its meant to describe the state of a widget with classes. Then the css rules interpret the classes to display the correct visualization of that state.
So for example when describing tab you shouldn’t give an element classes like “round-top” and “highlight” instead give it “tab” and “selected” Then use SASS or LESS mixins to define .tab with .round-top() and .selected with .highlight()
Oct 31, 2012 @ 14:23:02
Andy’s right. This technique means that you’re effectively controlling your styling in the HTML, not the CSS. Say you’ve got an element with a border radius class. If you want to remove the border radius, you’d be doing it in the HTML, not the CSS.
My point is, if you’re going to do it this way, you might as well be using the style attribute.
Oct 31, 2012 @ 14:23:49
To me, this seems like a DRYed-up return to inline style declarations. In code, this:
class=”content-box last-box corner-box pad-box”
and this:
style=”margin: 20px 0; margin-bottom: 0; border-radius: 4px; padding: 20px;”
seem, IMO, nearly identical except that the former has symbolic names.
The expanded form above also shows a potentially annoying way for microclasses to leak implementation details – in particular, touching the same CSS attribute in multiple classes is resolved based on source-ordering in the stylesheet. I’ve put together a short example:
http://jsfiddle.net/mzKYm/
Oct 31, 2012 @ 14:55:03
Chris… you’ve beaten me to a post I’ve been wanting to write about for a while. I’ll definitely be referencing this article when I get mine going.
My method for namespacing is as follows:
1. I use the greek alphabet as my basis for creating modifiers of classes.
2. Any padding / margin measurements used in a []-alpha class will be preserved for all modifiers using -alpha.
i.e. m-alpha, mt-alpha (margin-top), mb-alpha etc. will all use 1rem of margin respective to where the class name defines it. m-beta etc. will then use 2rems (I use rems as much as possible, with px fallbacks, as they do the heavy lifting of variables, while ensuring consistent spacing everywhere).
3. Colours are named similarly. If I set $clr-alpha to red, any class applying red will explain that in its name.
i.e. .fc-alpha { font-color: $clr-alpha;}
This way I know what colour is applied where, and it gives me the freedom to redefine the colour value as and when I please.
4. All media query specific modifiers are similarly namespaced. Default styles are not viewport namespaced.
i.e. .m-alpha applies to all viewports, m-alpha-vpalpha applies to mobile and up, m-alpha-vpbeta applies to tablet and up, and so on.
People may shoot this methodology down, but I’ve found it invaluable in a large project I’ve been working on that requires limitless scalability. Everything makes sense, everything is easy to style exactly how I want, and I VERY rarely ever have specificity issues.
I’m glad to see other people talking about this style of writing CSS. Nicolas Gallagher recently tweeted about one of his repos using this very style – it gave me goosebumps.
Classitis isn’t the disease, it’s the cure.
Good job, Chris!
Oct 31, 2012 @ 19:37:37
Thanks for reading, folks. I figured I’d get some constructive criticism for this post, because, as I said, a year ago, I would have found it odd myself.
However, a year ago, I was working on much smaller projects (web “sites”, as opposed to web “apps”). I adopted this method of writing CSS and markup because I was so sick of giving an element a unique class (with some fudged semantic name) just so I could, say, tell it to center its text and display in a slightly smaller font size. Do this a few times on a WordPress site, and nobody’s the wiser. Do it on a large application, with a client who likes to change things around a lot and is constantly iterating and adding new features, and those classes add up to the point of making your CSS a real pain to maintain. “What if,” I thought, “I just had a toolbox of classes that took care of these common, low-level presentational duties that I keep repeating over and over?” And that’s how the whole microclass thing started for me.
To those commenters who liken microclasses to inline styles, I’m not buying it. Yes, both allow you to assign presentation to an element in the markup (which, I argue in my post, is part of their awesomeness), but there’s a HUGE difference between style=”padding: 20px” and class=”pad-box”. The latter is an easily maintainable and editable class, whose value across an entire app can be tweaked to your heart’s content by simply changing a single line of CSS. The former is, well, an inline style, and we all know they’re bad news.
@Andy and the semantic HTML crowd — I hear ya. Philosophically, I love web standards. I go out of my way to write well-structured HTML. In fact, I’m totally “that guy” in this article (http://coding.smashingmagazine.com/2011/11/11/our-pointless-pursuit-of-semantic-value/) who spends 15 unbillable minutes on html5doctor agonizing over whether I’m using a new element correctly. And yeah, in a perfect world, all my divs would be assigned single classes that perfectly and concisely describe their exact semantic value to any front-end developer who cared enough to look under the hood (because Google honestly does not care).
BUT.. it’s 2012. Almost 2013, in fact. The original “true nature” of CSS was indeed to separate presentation from content (a beautiful thing); but these days, CSS has been forced to do more. Countless ids, for example, are being written into markup every day for the exclusive purpose of being hooks for javascript that makes applications run. There’s nothing semantic about them, but javascript is everywhere, and I think using classes to style and ids to manipulate the DOM is a smart way to go, given the way things have turned out.The same holds true for HTML — originally a markup language for academic research papers that has been imperfectly shoehorned into an application platform. So while I always endeavor to respect the semantic web as much as possible, my hat gets tipped to whatever way of working allows me to deliver the best value to clients. And for me, this is it, hands down — even if that means hinting at presentation in my markup.
Finally, @Larry – thank you. Would love to learn more about your approach. Who knows, maybe we could turn it into a framework??
Nov 01, 2012 @ 04:35:22
haha, a framework would be awesome.
I’ve already started putting together an article outlining my processes and structures. I should have it ready within the next week. I’ll give you a shout when it’s ready, but you’ll be getting a trackback anyhow.
Nov 01, 2012 @ 13:02:35
I’m doing a similar technique with my framework as well. Honestly, I’m never going back to the traditional way. People can argue back and forth what’s “the right way” to do things, but in the end, honestly, who really cares? Make it work in all browsers with as little effort is my goal. Doing things with microclasses has completely changed my workflow efficiency and I spend far less time dealing with browser issues to support a very large codebase.
Nov 01, 2012 @ 13:14:04
Preach on, brother Travis
If you ever have time, I’d love to learn more about your framework/way of using microclasses.
Nov 01, 2012 @ 20:58:20
*facepalm
I work on small and very large sites/apps, and this is bad for many reasons. The next developer to take on your projects is going to be punching walls.
You’re creating a dependence on this new class naming language.
If you are working on projects where you can’t use SASS, maybe try LESS.
The problem with the form example you gave, is you should have targeted the styling with a class name rather than the element to begin with. Then any overriding you needed to do would be done with one class name addition that described the element not it’s styling. No long selector chaining or ID styling necessary.
I get what you are trying to accomplish, but to me this approach has many of its own issues. And there are “best practices” to help with if not completely solve some of the troubles mentioned in your article.
As Matt mentioned, this does take you back to the idea of inline styles but worse – cause now the slightly small defined class name is hiding the not much bigger inline styled css. You gain the advantage of making a change in one place, which actual OOCSS already provides you.
This is far from being Object Oriented.
Nov 02, 2012 @ 03:58:11
Chris – I would agree with you that ivory-tower “this isn’t semantic” arguments ring increasingly hollow down here in the trenches.
But there are basic practical advantages to separating style and content too and it’s a shame to throw out the one big idea of CSS when there are better ways to achieve the same ends.
Nov 02, 2012 @ 08:44:20
Thanks for reading, @Nick. I think we’ll have to agree to disagree on this one, so take that palm off your face, my friend, and cheer up! It’s only CSS.
To your points:
“This is far from being Object Oriented.” First, I understand what OOCSS is, and I never said microclasses are OOCSS. As it the title of the post states, this approach is *inspired* by the goals of OOCSS (speed, reusable code, avoiding duplicating styles).
“If you are working on projects where you can’t use SASS, maybe try LESS.” Not sure where you’re getting this: I mention a couple of times in my post that I use and adore SASS. I consider it a really powerful complement to microclasses. For example, if you declare a variable called, say, $spacing, then add it to your padding classes as follows…
.pad-box { padding: $spacing } .pad-box-micro { padding: $spacing/2 } .pad-box-mega { padding: $spacing*2 }
… and you get some feedback from your client saying things are looking a little cramped in your app, you can adjust every instance of padding by simply tweaking your $spacing variable.
YES, you can absolutely get the same result by, as you prefer, creating single, defined classes for everything, and declaring the $spacing variable in those. And don’t get me wrong, I still write a lot of app-specific classes (I feel like my post has given readers the impression I *only* use microclasses). But when working on large projects, I got so sick of having to create — and dream up “semantic” names for — entire classes because I needed to achieve common, low-level presentation like centered text, background color, padding and margin. I also got frustrated when I’d define your typical OOCSS content “module”, then the client would ask for an exception (“These gray boxes look really great, Chris, but can we make them orange when they contain a call to action, and green when they contain a sign-up form?”). So I’d be adding still more unique class names to modify my content module and make these tiny tweaks.
To continue with the example above, these days, when a client asks for an orange box instead of standard gray one, I just swap out my .mid-bg microclass for .brand-color-bg, and move on with my life. And in my mind, there’s a big difference between .brand-color-bg (an abstracted class that’s tied to a SASS var that contains that client’s central brand color) and something like .green-box that overtly describes specific presentation.
“You’re creating a dependence on this new class naming language.” I’m flattered you think I’ve created a whole new language, but it’s really just a different approach to writing styles and markup that I thought I’d put out there to see if anyone else finds it useful.
Nov 02, 2012 @ 08:45:18
@Andy – Agreed! And thanks for reading. I know this isn’t for everyone, but I am glad for the discussion.
Nov 02, 2012 @ 18:17:21
Why not use Mixins or Selector Inheritance with SASS to achieve exactly what you are doing while keeping styling and markup separate? So if you had a form with a class of “register”:
.register {
@extend .content-box;
@extend .shadow-box;
@extend .blue-background;
}
This form could inherit a base form styling as well.
Simple Methods For Writing Scalable CSS Now | Mouse Potato
Nov 11, 2012 @ 11:33:05
[...] to dream up new names for them. Chris Hart wrote about this style of modifiers in his article on describing in the browser with OOCSS-inspired modifiers, and Necolas Gallagher has a useful library full of these utility [...]
Dec 23, 2012 @ 07:07:35
I really like this idea. The modularity of it. However I also agree with nick about the use of mixins being more appropriate.
Example of why: csszengarden.com
So I think you could think this out more and achieve the results you want to achieve, in a way that is more… semantic; flexible.
I like to scope things to div classes and actions when writing SCSS, like “.member .show” and also have SCSS files that mirror controller structure. So for this I would put my mixins /custom definitions in there, and then have some scss lib directory that actually defines everything like “.dark-shadow-mini”
This split still lets you work in a modular way with your elements, while keeping the dom clean if you wanted to have something totally different for mobile, for example.
Regardless, thanks for this post. Keep pushing this methodology!
Mar 10, 2013 @ 08:17:58
I’m sorry, but I’m a hater! While this is an interesting approach with several benefits that you outline, I feel these could be achieved in other ways and that there are also some drawbacks.
1. Semantics!
A key purpose of CSS is to separate content and style. If you start describing style in the HTML, and CSS is simply the elaboration, you lose this abstraction and its benefits. In particular…
2. DRY?
…higher level design changes (e.g. “from now on, only important messages will use drop shadow”) become difficult to implement. In a sense, your CSS has become DRY but your HTML is soaking. Between the 2 documents you are in fact repeating yourself, just in 2 different languages.
3. Frontend Speed
Putting standard style information in one file means the browser downloads spartan HTML, and then CSS, with no functional overlap, and then going forwards doesn’t need to download the CSS again, improving speed. By littering your HTML with style-based classes you lose this benefit as the style information is downloaded every time with the HTML.
Solution
It’s uglier and harder to maintain, but for the sake of a better website, you can achieve the same thing by grouping related selectors:
.error, .message, .content, .post { color: red; text-shadow: white; box-shadow: etc }
This keeps both your CSS and your HTML DRY.