Jeff Croft

I’m a product designer in Seattle, WA. I lead Design at a stealthy startup. I recently worked at Simply Measured, and previously co-founded Lendle.

Some of my past clients include Facebook, Microsoft, Yahoo!, and the University of Washington.

I’ve authored two books on web and interactive design and spoken at dozens of conferences around the world.

But seriously, who gives a shit?

Blog entry // 05.20.2009 // 12:34 PM // 91 Comments

On applying OOP concepts to CSS

Last night, while work on a very cool client project for Blue Flavor, I took a short break to make the following tweet: “It’s amazing what you can do in very little code when you apply object-oriented principles to CSS. Wish more front-end devs understood OOP.”

I got a surprising number of responses from people asking what I meant, exactly, and for examples. I also got several responses, and a few IMs, from people touting Compass and Sass, a pair of Ruby projects that provide useful language features and syntax to CSS and CSS frameworks, allowing you to do all sorts of fancy things.

The OOP concepts I was specifically referring too are mostly around inheritance, co-reuse, and the Don’t Repeat Yourself (DRY) principle. Think subclassing, mix-ins, etc. Clearly, CSS doesn’t provide this kind of syntactic sugar, and it’s very debatable whether it should or not. The W3 is strongly against even adding variables (or constants) to CSS. I personally am in favor of variables in CSS, but would be against adding much logic to the language. So it becomes a question of where to draw the line, and I strongly suspect the slippery slope is why Bert Bos is so vehemently opposed to variables.

So while CSS doesn’t offer real subclassing or mix-ins, it does allow for something that can (sort-of) replicate that functionality: multiple classes per element. For example, I can make a class of .box that defines some basic layout structure, and another class of .rounded that provides rounded corners, and classes of .wide and .narrow that define some widths, and then easily create boxes of varying widths and styles by assigning multiple classes to an element, without having to duplicate code in my CSS.

Of course, there are two big issues with this that are causing the Andy Clarke’s and Jeremy Keith’s of the world to throw up in their mouth a little bit as they read this: so-called “classits”, as well as so-called “non-semantic” class names. So allow me to address each…

Classitis” is a popular terms for using too many classes. The first time I was warned against class over-use was way back when Zeldman first released Designing With Web Standards, and at the time, it made good sense to me. However, having learned about object-oriented programming over the past few years (through Python and Django), I’m not sure I still agree. If I have 100 “boxes” on a page, and 75 of them use rounded corners, and 20 of them are wide and 80 are narrow, I basically have two choices.

First, I can create a bunch of classes. For simplicity, let’s call them .box, .box-rounded, .box-rounded, .box-wide, .box-rounded-wide, and so forth. You can see that several of these would be required to cover all the possible box styles. And what’s worse, each of them includes a lot of duplicate code. They all need the basic box structure. Several of them need the rounded corners. And so forth.

The other option, as I said above, is to use multiple class names on an element. So, you end up with <div class="box rounded wide">. The advantage here is around maintainability: in your CSS, you no longer have to repeat the code for the base box structure over and over again, which means when you change it, you only have to change it in one place. And I think we can all agree that the extra code that it takes us to use three class names is far less than the extra code it takes us to redefine a box three times in CSS. So I say get over your fear of multiple classes. Having five classes on one element is nothing to be ashamed of.

So on to those presentational class names: first, it’s worth noting that I’m only using them here because a box with rounded corners at varying widths is simple for us all to understand. These concepts certainly apply whether it’s called .box or .navigation. Second, I would (and have, several times in the past), question exactly what the reasons are for avoiding presentational class names. While I do advocate being as semantic as possible, it’s important to note that presentational class names cause no real-world problems of note. So, I’m all for being semantic, right up to the point where doing so is disallowing me to stay DRY, making me less efficient, and bloating the hell out of my code. That having been said, I’d never actually use a class name like .box-rounded-wide, and I hope you wouldn’t, either. It just makes for a good example. Bottom line: the only thing you really gain from using 100% semantic class names all the time is that Jeremy or Andy get a little tickle in their loins when they view your source. If that’s important to you, then by all means, be semantic.

Okay, so what about Compass, Sass, and similar projects? Before I tell you why I don’t think they’ll work in a lot of cases, let me be clear: these things are very cool. I’m very impressed by Sass, especially. It’s powerful as hell, offering elegant language features to CSS. No doubt using Sass produces cleaner results than using just piling on the class names, like I’m suggesting.

But the one big looming problem with these projects is this: they’re for programmers. Sass may seem pretty simple to you, but I guarantee you it would confuse the hell out of most of my co-workers — and my co-workers are all fucking brilliant designers and front-end developers. The problem is simply that most designers and CSS authors aren’t programmers. What’s more, most of them don’t want to be programmers. As soon as you start talking about mix-ins, subclassing, and passing arguments, their eyes roll into the back of their head. Applying multiple classes to an element, though? That, they can understand.

So, what was the impetus for my tweet? Basically, I meant not being afraid of multiple classes, even if they’re borderline presentational, and thinking of CSS classes as objects that can extend one another (even though they technically can’t). However, this is really only the tip of the iceberg as far as applying OOP concepts to CSS. Nicole Sullivan recently did a talk on Object Oriented CSS and touches on many other aspects, almost all of which make perfect sense to me. It’s a great place to start for more info on this sort of thing. If you don’t have some basic understanding of OOP concepts, the benefits of this stuff may still be lost on you a bit. That’s fine. You’ll come around. :)

For the record: I joke with puritans Jeremy and Andy because they’re friends and I know they can take a little ribbing. I love both those guys — nothing personal intended!

Update: My rounded box examples were shit. I should have taken the time to come up with some good, non-presentational examples, to avoid the semantic/non-semantic part of this post all together. Matthew Anderson posted a comment below in which he provided much, much better examples: “Messaging in applications is a great example. Your success, informational and error messages should have a similar look and feel. Using classes like “success message”, “info message” and “error message” are no less descriptive and no less communicative than “success-message”, “info-message” and “error-message”. However, they are a lot more maintainable and you accomplished it with less code.” Perfect!

Comments

  1. 001 // Anton D Peck // 05.20.2009 // 12:44 PM

    I have a habit of doing something similar. When I create a project, I tend to habitually create classes for: .fleft, .fright, .tleft, .tright, .tcenter, .clrleft, .clrright, .and .clrboth. You can pretty much guess from the names how I use them. :)

  2. 002 // Mark Wunsch // 05.20.2009 // 12:46 PM

    This is something we actually we work on a lot at Scripps Networks (http://foodnetwork.com, http://hgtv.com) and we are constantly working on improving our CSS library.

    One thing we work on is what we’ve come to call a “cartridge” — I’m not sure how that name came about. A “cartridge” is a markup pattern, that when placed within a container with a given class name, inherits all kinds of goodies. In OO terms, the CSS class name “instantiates” the cartridge.

    That way, we can reuse patterns of markup that seem to appear over and over again, and give them new presentation based simply on their context with one class name.

    Great post!

  3. 003 // Kyle Fox // 05.20.2009 // 12:49 PM

    I find multiple CSS classes especially useful for interactive elements; things like tabs, for example. There is something very zen about writing JavaScript that adds or removes classes (such as “selected”) from an element and then keeping all the rules that define the presentation of “a tab in the selected state” in your CSS.

  4. 004 // Baxter // 05.20.2009 // 12:53 PM

    I think the argument against classitis has at some point morphed away from what was originally intended. I believe it was initially intended as a warning to not put a class on every stinking element, and instead use the DOM and child selectors. At some point, some people have come to the conclusion that classes are bad, mmm-kay.

    Personally, I’m much rather see class=”this that the-other” than a crapload of classes on child elements—or worse yet, a crapload of superflous child elements.

    And semantic class names are a worthwhile and noble goal, but they’re trumped by classnames that the next guy is going to understand. Class names are SUPPOSED to be somewhat generic. If it was unique, you’d be using an ID.

  5. 005 // Mykola Bilokonsky // 05.20.2009 // 12:56 PM

    I recently found myself writing CSS for the first time in a really long time - I’ve been doing Flash/AS3 for the past year or two, and in the process learned a lot of OOP practices.

    I completely agree with your assessment. That approach, though, places some constraints on your designers - it was very frustrating to get a .psd on this recent project, for instance, where many measurements were obviously eye-balled. There were a lot of narrow boxes all within about 3 pixels of each other in width, font sizes were all out to two decimal places and never identical, etc.

    Granted, one could argue that this is simply unacceptable from a design professional in any context - but it seems more egregiously wrong when you start thinking about your CSS in object-oriented terms.

    Someone should start an Object Oriented Design crusade, it would make the collective jobs of web developers everywhere about 20% easier.

  6. 006 // Garrett Murray // 05.20.2009 // 12:58 PM

    Classitis” is one of the stupidest things I’ve ever heard. The reason they’re called CASCADING style sheets is for this very purpose. It makes zero sense to create a full style block for each item if they share common elements and can be stacked. Honestly, I don’t think that being against this EVER made sense.

    Furthermore, presentational versus semantic class/id names don’t make a difference. Personally, I’m with you: I use semantic names if it makes sense and allows me to not repeat. But I could care less how semantic the class names are if it requires me to re-write the same CSS over and over and over.

  7. 007 // Kyle Jacobson // 05.20.2009 // 1:01 PM

    Re: semantic class names, hopefully there are semantic links between all elements of the same dimensions (e.g. all supplementary content with equal place in content hierarchy [though one could argue if two elements should ever get equal weight]) or with rounded corners (e.g. all topical content, such as blog posts, etc.). It’s a good way of ensuring that aesthetic decisions have a rationale, and allows one to avoid the non-semantic class name problem.

  8. 008 // Chris Griffin // 05.20.2009 // 1:29 PM

    Jeff & Garrett,

    In full agreement, keeping my CSS DRY is priority #1. Stylesheets can easily turn into a big pile of mess on bigger projects as it stands. If presentational or multiple classes helps avoid duplication of CSS, I will, without hesitation, use multiple and/or presentational classes. It’s a matter of being making choices that keeps your CSS lean and efficient, and it can definitely be done in a sensible manner.

    People who speak out against this practice are usually idealists, and I never find their arguments to make much sense.

  9. 009 // Rene // 05.20.2009 // 1:40 PM

    That was a good read. This would be an interesting approach to keeping CSS files lean and mean, and something I never gave too much thought.

    You mentioned learning OOP & Python/Django recently. Can you make any book recommendations?

  10. 010 // Dan Rubin // 05.20.2009 // 1:41 PM

    I’ve been using the multiple class approach for the last year+ on client projects — it makes things so perfectly modular that once I started seriously using it I couldn’t believe I hadn’t been doing it that way from the very beginning.

    And ditto @Garrett’s and @Baxter’s comments above, the concept of “classitis” is silly when used to argue against using CSS as it was designed (I too have always taken it to mean not putting a class on every element, rather than “don’t have too many classes”).

    I sense a full revision of Pro CSS Techniques in the future… ;)

  11. 011 // Matthew Anderson // 05.20.2009 // 1:41 PM

    Great post, Jeff!

    The most important distinction for me regarding semantics has always been this follow up question:

    What is the purpose of class names?

    In my opinion, they are for:

    • Communicating with others who will be maintaining the code
    • Describing the type of content they are classing
    • Making your (hopefully already semantic) HTML even more maintainable

    With these purposes in mind, I simply don’t understand the majority of arguments surrounding absolutely unique class names. Here’s why…

    Messaging in applications is a great example. Your success, informational and error messages should have a similar look and feel. Using classes like “success message”, “info message” and “error message” are no less descriptive and no less communicative than “success-message”, “info-message” and “error-message”. However, they are a lot more maintainable and you accomplished it with less code.

    Bottom line - if you find yourself in a situation where stacking your classes means that you will be less likely to need to revisit that code - why wouldn’t you?

    I had a little bit more to say about this in a recent Onehub blog post on selecting a CSS framework.

  12. 012 // Dave Gregory // 05.20.2009 // 1:47 PM

    I was completely overwhelmed when I read about OO CSS from your tweet Jeff. Every site I work on, always ends up with too much css and alot of repeated or similar styling. Same goes with the “modular” style of writing css. It invites code bloat from the getgo.

    I came away from her video with a few really good points:

    Independent sections of code acording to function

    ie..separate the grid(template), module(skin/box), and content code. This is great because it’s like giving yourself infinite possibilities with your current styles. for example:

    making 4 styles for a list and having them be completely independent of the box they are contained in, will allow you to use them anywhere on the page* This also creates a living style guide for you to enforce current styling over creating “one-off” styles that only get used once.

    Scalability

    I envision telling my designer, that the page he really doesn’t want to mock up because it’s boring… “do a wireframe” and I wil make the page without touching css at all. The styles are there, it’s just a matter of mashing them all together using markup and classes on key areas.

    Development is less difficult / time consuming

    Creating semantic markup would then become the emphasis. Not “how can I style this markup?”.
    This would free me up to more work on accessiblity and all the other front end issues that always get put off.

    I have coded using SMF and multi-classing, so much of this is straight forward for me, which makes it even more enticing to use in my next project. Happy Dayz!

  13. 013 // Chris Forrette // 05.20.2009 // 1:49 PM

    Where I work we utilize a hybrid of these, where we have a set of generic class names we usually port to every site (identical to @Anton D Peck above, but .fl, .fr, .cf, etc..) and that’s mixed in with more specific class names, like ‘box-left-feature’, etc. I would love to adopt a full “classitis” method to things but unfortunately we still support IE6, and there is the inevitable issue of multiple class styling not working, e.g.:

    .box.rounded { /* Something very specific to a rounded box */ }

    Have you devised any workarounds for this? I would love to hear about them.

    I propose organizing some sort of angry mob to rid the world of IE6, because there are so many great methods/ideas/what-have-you like this that are thwarted by that dinosaur of a browser.

  14. 014 // Chris Eppstein // 05.20.2009 // 1:51 PM

    @Kyle Jacobson

    I think you hit the nail on the head there. I don’t advocate semantics for semantics’ sake, I use class names on my sites that are more presentational in nature, but they still convey meaning within our site’s design vocabulary even if they are shared across data of disparate types. For instance we might use “.informational”, “.interactive”, and “.call-to-action” to represent the various color schemes we use for boxes and buttons. In an object oriented world, this is called multiple-inheritance or a decorator pattern.

    The goal should be to express the design concepts of your site in as close to the design vocabulary as the designer has created, because changes to the design will tend to preserve the design concepts even when the implementation of those concepts varies over time. And when the concepts change, well, pretty much all bets are off from both a design and an interaction perspective.

    Sass helps avoid classitis, by simplifying the creation of sub-selectors so that you needn’t permute your class names when their meaning is largely unchanged but the context requires a difference in presentation.

    I disagree that Compass and Sass are “Programmer’s Stylesheets.” Maybe it is true, but I don’t jump to that conclusion and eagerly seek feedback from designers about what they like and don’t like about Sass (several syntax changes are forthcoming as a result). But to write them off out of hand I feel is an insult to them. Designers work in a world of abstraction and concepts — I think they can and should use tools that allow them to describe the world in the way they think about it. This is why object orientation is creates reuse and maintenance gains for programmers, and I’m pretty sure it’s why so many designers who use Sass, tell me how much they absolutely love it.

    Thanks to Jeff for the thoughtful write up and the kind words you said about Sass & Compass.

    Chris

  15. 015 // Jeff Croft // 05.20.2009 // 1:51 PM

    Re: semantic class names, hopefully there are semantic links between all elements of the same dimensions

    Often times that is the case, and if there are such semantic links, i’d definitely advocate taking advantage of them. If there aren’t, I wouldn’t get too up-in-arms about it.

    I sense a full revision of Pro CSS Techniques in the future… ;)

    You’re on your own, buddy. ;)

    @Matthew Anderson: Love your message example. With I’d thought of that instead of my “box” example, as it’s more real-world and shows that this stuff doesn’t have to apply to presentational names.

    Glad to see most people on the same page with me, here. I was worried this would again be a controversy-inciting post, and I’d finally be burned at the stake by standardistas still stuck in their 2004 ways. :)

  16. 016 // Faruk Ate? // 05.20.2009 // 2:07 PM

    Chris (#13):

    You can work around IE6’s lack of support for multiple-class selectors by using cascading rules and specificity. Yes it makes your code a little more fragile, but it won’t prevent you from using multiple classes. It just means you won’t multi-class any selectors, you’ll just use more descendent selectors, e.g.

    div#parent .box { // } div.different-parent .box { / different … / }

    Jeff et al:

    IE6 is a big reason why people haven’t used multiple classes much yet. It’s lack of support for multi-class selectors (i.e. .foo.bar) has prevented its widespread adoption. Now that fewer and fewer sites are requiring IE6 compliance (at last), it’s a good time to start spreading the word on these better techniques.

    BTW, for what it’s worth, I don’t find systematic CSS architectures such as this OOP-CSS style any less semantic, as long as your class names are semantic themselves. In other words, not this:

    .blue { color: blue; } .bigfont { font-size: 16px; }

    Your example of .wide is a little questionable, I’d see if there wasn’t a better name for it. The example of .rounded is perhaps inevitable, if for no other reason than the fact that it appears that rule IS purely for styling purposes only.

    Some cruft in the semantics of a page should be overlooked if it results in significantly cleaner and more manageable code.

    My two cents, anyway.

  17. 017 // Jeff Croft // 05.20.2009 // 2:15 PM

    @Chris Eppstein:

    For instance we might use “.informational”, “.interactive”, and “.call-to-action” to represent the various color schemes we use for boxes and buttons.

    Totally agree with you on this stuff. It absolutely makes sense to use this kind of vocabulary wherever possible. But there are, occasionally, times when it’s just pretty much unavoidable to use a more presentational name, and when that situation arises, I don’t sweat it too much.

    I disagree that Compass and Sass are “Programmer’s Stylesheets.”

    That’s fair enough. Look, I definitely didn’t mean to insult them at all. I’ve very impressed by the work that has gone into them. I just know my community of designers-who-knows-CSS very, very well, and I know that for many of them, as soon as you tell them to open terminal, they laugh in your face. Take them out of their beloved CSS Edit or similar, and they’re going to be very uncomfortable. I’m not saying that’s okay — it’s not. They should be more willing to learn new languages and technologies. But I’m telling you, many of them just aren’t. It’s the reason so many designers are still using FTP and not using version control.

    Designers work in a world of abstraction and concepts — I think they can and should use tools that allow them to describe the world in the way they think about it.

    Absolutely agree. The irony here is that the designers who are doing more abstract things, creating design systems instead of designing web pages, are both the people most likely to push back on anything that requires them to do programming and also the people who could benefit from it most.

    Again, I love Sass. And Compass. Great, great stuff. I just know that many designers will simply not be comfortable in any environment that requires them to understand concepts like inheritance, mix-ins, default keyword arguments, and the like. They’re designers, not technologists, and for many of them, that’s how they want to stay.

    Chris, it definitely wasn’t intended as an insult on your work at all, and I’m sincerely sorry if it sounded that way!

  18. 018 // Nicole Sullivan // 05.20.2009 // 2:20 PM

    Thanks for the link-love.

    I think you would be surprised how many designers I’ve worked with instinctively understand objects. One even said to me, “Objects? They think we don’t understand objects? Objects are around us all the time!”

    What they don’t know are the programming words used to describe objects like mixins, subclasses, etc. We just need to explain it with a lingo-free vocabulary (yes, this takes longer). Then designers find OOCSS much easier.

    @ FARUK ATE? You don’t really need to specify multiple classes… the “winning” values just need to be later in the CSS file. This is why OO + Cascade is so powerful.

    Nicole

  19. 019 // Jeff L // 05.20.2009 // 2:23 PM

    Like some others, definitely think you misunderstand “classitis.”

    Your example is not classitis. Classitis is something more like applying a class to every list item in a list instead of simply putting a class or ID on the main ul and inheriting styles from there.

  20. 020 // Jason O'Brien // 05.20.2009 // 2:27 PM

    You say “presentational class names cause no real-world problems of note” but I would disagree.

    If a box has .rounded but you no longer want rounded corners on it, you either have to apply another class to it, or take off the .rounded.

    However, if the box was called .info, you can change the styling however you want without messing with the markup. This is partly why CSS was created.

    If there’s a concern about 30 different boxes having the same repeated styling, group them together like:

    .info, .something, .another { styles }

    And then if one needs to change, you can break it out or override it.

    Just sayin’, because I never use more than two or three classes on something, even WITH using grid frameworks.

  21. 021 // Tim Kadlec // 05.20.2009 // 2:48 PM

    I have to agree with Dan, I’ve always thought class-itis was more about how not every element needed to have a class assigned to it then it was about the number of classes.

    I haven’t experimented with OOCSS enough to form a definite opinion, but so far I’ve been very pleased with the results and the concept makes a lot of sense to me.

    It’s a bit of a change in mindset for a lot of people, but it really harnesses the power of CSS’s cascading capabilities to provide a much more powerful, and in my opinion more elegant, way of laying out designs.

  22. 022 // Andrew Ingram // 05.20.2009 // 2:54 PM

    I’m still undecided, I’ve tried this approach on a recent site build, using loads of highly modular styles and to be honest it ended up being a maintenance nightmare every time we wanted to change things in certain ways.

    If one of my designers sees a ‘user message’ on a page and wants to use it elsewhere, all he should need to know is to find the user-message class and apply it to a div. He shouldn’t have to think ‘hm, well the user message has a blue border with rounded corners, so I have to use use the blue-border and rounded classes as well’, this is bad because it means your markup gets littered with all these classes and it becomes a much larger undertaking if you then decide that user messages should actually have chiselled corners with yellow borders - you have to find every place where you use user messages on the site and change all those classes.

    What you’re describing is, in my book, the opposite of Object-Oriented, you’re describing the element to be styled based on its attributes rather than its intended function.

    The more natural approach is to define the style for a user-message, but if you have a slightly differing presentation in a few cases, create a use a ‘alt’ class with .user-message.alt which overrides the defaults. This is a lot closer to being OO.

    I think proper inheritance and variables, as well as more advanced logical constructs, are essential to the future of CSS. The fact is that there are certain kinds of layouts that simply cannot be described without some degree of logic, the trick is to find a syntax for this logic that is designer-friendly rather than just programmer-friendly

    Basically, if you’ve got ‘rounded’ classes sprinkled throughout numerous template files, you’d better hope someone doesn’t suddenly decide that actually they don’t want rounded corners on 3/4 the elements anymore.

    Using ‘semantic’ markup may seem excessively purist, but give me repetition in my CSS over my HTML any day - for the simple reason that most of my CSS will be in one file rather than dozens. Should the day come when I have to change the roundedness of a corner, sure I may have to make the change a dozen times (unless we have inheritance in CSS…) but I’m doing it in one place and it’s still relatively quick.

  23. 023 // dvessel // 05.20.2009 // 3:04 PM

    Jason O’Brien, since CSS is static it becomes very hard to manage especially when it goes through multiple people who have their own ideas on how things should be done.

    Using class names is a no brainer. In CMS’s and frameworks they can be generated on the fly with predictable rules. It’s no guarantee that the back end won’t become a mess but it’s easier to manage there.

  24. 024 // Andy Clarke // 05.20.2009 // 3:11 PM

    Of course, there are two big issues with this that are causing the Andy Clarke’s and Jeremy Keith’s of the world to throw up in their mouth a little bit as they read this: so-called “classits”, as well as so-called “non-semantic” class names.”

    — No, actually I completely agree and I work largely the same way. So if you were expecting a fight, you ain’t going to get one — you big fat girl’s blouse! ;)

  25. 025 // Michael Dick // 05.20.2009 // 3:31 PM

    Using “.box .wide” is perfectly sensible. However, the part that gets me is when people go a step further and apply .float-left, .float-right, .clear-left, .clear-right, and so on…

    What’s the difference between using style=”clear: left;”. There is none. Wait. Yes there is, the later has a higher specificity. My bad.

  26. 026 // Jeff Croft // 05.20.2009 // 3:33 PM

    I think you would be surprised how many designers I’ve worked with instinctively understand objects. One even said to me, “Objects? They think we don’t understand objects? Objects are around us all the time!”

    Good stuff, Nicole! You’re doing a great job of making this stuff easier for non-programmers to understand. That’s awesome.

    If a box has .rounded but you no longer want rounded corners on it, you either have to apply another class to it, or take off the .rounded.

    No, you don’t. You can simply change .rounded in your CSS to have square corners. Sure, now your name doesn’t make very much sense, but absolutely no real-world issues are presented because of this. And, as I’ve said many times, I would certainly try for something more semantic where possible, but sometimes it’s just not possible.

    Just sayin’, because I never use more than two or three classes on something, even WITH using grid frameworks.

    That’s great. But why is two or three classes better than five? It’s not. I’d use as few as you need in order to keep yourself DRY. If you need five, then by all means, use five, and don’t feel bad about it.

    I have to agree with Dan, I’ve always thought class-itis was more about how not every element needed to have a class assigned to it then it was about the number of classes.

    Perhaps — but whether it’s called “classits” or not, there definitely is some opposition to multiple classes per element. It was a huge part of the backlash aganist Blueprint and its ilk, when they were new.

    The more natural approach is to define the style for a user-message, but if you have a slightly differing presentation in a few cases, create a use a ‘alt’ class with .user-message.alt which overrides the defaults. This is a lot closer to being OO.

    That’s exactly what I’m describing, isn’t it? I don’t see the difference at all. The only difference is I wouldn’t use a meaningless name like .alt, because I’ll never remember what “alt” means. And what if there are two variants? “alt-2?” no thanks. I’ll take “rounded” and “chisled” over “alt”, because at least they have some meaning.

    But the concept seems exactly the same as what I’m describing, to me.

    I think proper inheritance and variables, as well as more advanced logical constructs, are essential to the future of CSS.

    I’m a bit undecided on this one, myself. I’d certainly personally like to see them included, but I’m undecided as to whether it’ll actually be good for the language and the community.

    Basically, if you’ve got ‘rounded’ classes sprinkled throughout numerous template files…

    Only I clearly said in the post that i would never use .rounded as a class name, and that I only used it to illustrate my point.

    Using class names is a no brainer. In CMS’s and frameworks they can be generated on the fly with predictable rules. It’s no guarantee that the back end won’t become a mess but it’s easier to manage there.

    BINGO!

    No, actually I completely agree and I work largely the same way. So if you were expecting a fight, you ain’t going to get one — you big fat girl’s blouse! ;)

    Dammit, Andy. You’re no fun. We could have had an awesome fight over this. :)

  27. 027 // Kyle Weems // 05.20.2009 // 3:43 PM

    Great post!

    Ever since attending WDN09 (and Nicole Sullivan’s presentation) I’ve been finding myself doing this more and more with classes.

    I’m in the camp of generally worrying about non-semantic names, but I’ll admit sometimes one fits better than anything else.

    The modular approach to classes for providing CSS support really helps cut down on the size of my stylesheets a lot. I worry every now and then about too many classes appearing all over the markup, but generally I’ve found the impact to be a lot lower than my initial concerns.

  28. 028 // Kevin Pang // 05.20.2009 // 3:53 PM

    Maybe I’m missing something, but doesn’t this break the idea that CSS should separate document content from document presentation?

    For example, expanding on your 100 boxes example. What if you wanted to change those 75 boxes back to being square corners? You would have to go into each of those 75 boxes and remove the “rounded” class since altering the “rounded” classes itself would affect other elements still using it. Worse yet, what if those 75 boxes are spread across 75 different pages? That would require you going into each of those .html files and removing the “rounded” class.

  29. 029 // Matthew Anderson // 05.20.2009 // 3:53 PM

    @Andrew Ingram:

    …all he should need to know is to find the user-message class and apply it to a div. He shouldn’t have to think ‘hm, well the user message has a blue border with rounded corners, so I have to use use the blue-border and rounded classes as well’

    I agree. However,

    …if you have a slightly differing presentation in a few cases, create a use a ‘alt’ class with .user-message.alt which overrides the defaults.

    I don’t think that effectively removes your stated requirement from your other designer. Could just be the example you used, but think about separating “user” from “message” (and subsequently clarifying “user”). I’m going to have no idea as to when I’m supposed to use the “alt” version of the “user-message”.

    Jeff’s .box example may have been a bit lackluster; look past the name he chose though, the concept is sound. Separate your classes in to chunks of reusable names.

    Other designers are going to be able to answer straightforward questions like, “is this an error” and “do I need it to span the entire screen”. These are both types of messages. So, in situations like these, it makes more sense to use “error message wide” rather than “user-message alt”, in my opinion. This allows you to individually manipulate any of the three classes and your other designers can still make very quick code decisions. If a time comes when “wide” doesn’t actually span the entire screen then, more than likely, the HTML around that is going to be changing as well. If not, simply drop the CSS declaration for it.

    See my original comment above for some more context.

  30. 030 // Erik Vorhes // 05.20.2009 // 3:54 PM

    Another way to deal with the “what if .rounded has styles we don’t want any more?” question: If the class only has information about rounded corners, just comment the whole class out of your stylesheet. In some ways, that might be preferable to changing the styling within the class, since there’s nothing counterintuitive about a class with no styling behind it.

    And it’s not as if HTML throws errors or warnings for class names that don’t have styles associated with them (unless you’re using MS Visual Studio’s horrid IntelliSense or whatever it is that scolds you about “undefined” class names).

    In any case, I’ve recently switched to the OO approach as well and find myself wondering why I ever did it any other way.

  31. 031 // Jina Bolton // 05.20.2009 // 3:57 PM

    You are wrong. That is all.

    (kidding!)

  32. 032 // Stephanie Sullivan // 05.20.2009 // 3:58 PM

    Well written, sir.

    I have to agree with you and many others here. Over the past couple years, I’ve begun using more and more multi-classing of elements. I believe that’s different than classitis (which is what I did on my first ever CSS site — every P element had the class=”main” on it! :O).

    Muti-classing is well-supported and simplifies many things. I talked about it at the end of my AEA talk last year. I use a combination of multi-classing and grouping selectors that have common properties.

    When I heard about the work Nicole Sullivan has been doing on OOCSS, I was intrigued. I’ve begun having a look at it and though I’m still on the fence about pre-made grid systems (I’ve always done my own thang), I really do appreciate her ideas and believe I’ll be implementing at least a portion of it.

    My biggest concern is not whether I can understand and implement it. I do a lot of coding for other companies to maintain — their skill level plays into the methods I choose to use. And their skill level’s vary widely. :)

    Thanks for writing this up, Jeff. After seeing your tweet last night, I was interested to hear your thoughts on it. :)

    Ciao… @stefsull

  33. 033 // Kevin Pang // 05.20.2009 // 4 PM

    @Erik Vorhes

    Commenting out the “rounded” class doesn’t work if, say, you want to disable rounded corners for only some of the elements using the “rounded” class but not all of them. Obviously there are pros and cons to any convention, but this is definitely one of the flaws with this design.

  34. 034 // W. Andrew Loe III // 05.20.2009 // 4:07 PM

    This style has one HUGE benefit that I haven’t seen anyone mention: speed. Upwards of %80 of the time waiting to draw a page is on the client side, by making your CSS extremely modular, you are also making it extremely light and you can programatically include only exactly what is necessary to draw the page. This makes your initial page load faster, and lets you add to the browser’s cache piece by piece. I guarantee everyone’s clients care way more about speed than semantics.

  35. 035 // Chris Eppstein // 05.20.2009 // 4:08 PM

    I just know my community of designers-who-knows-CSS very, very well, and I know that for many of them, as soon as you tell them to open terminal, they laugh in your face. Take them out of their beloved CSS Edit or similar, and they’re going to be very uncomfortable.

    Jeff, I didn’t take any offense. But it is a stigma, I’m working very hard to avoid. I have met a couple designers who were pulled kicking and screaming into the world of Sass and Compass by their dev teams. Once they got over their fears and the learning curve, they became advocates. Some have discarded their GUI editors because they become more efficient without them.

    Someday, someone will write a GUI front-end for compass. And if all goes well, maybe native browser support will eliminate the need for a compiler altogether ;-)

  36. 036 // Jeff Croft // 05.20.2009 // 4:10 PM

    Another way to deal with the “what if .rounded has styles we don’t want any more?” question: If the class only has information about rounded corners, just comment the whole class out of your stylesheet. In some ways, that might be preferable to changing the styling within the class, since there’s nothing counterintuitive about a class with no styling behind it.

    Bam! Great point.

    Commenting out the “rounded” class doesn’t work if, say, you want to disable rounded corners for only some of the elements using the “rounded” class but not all of them. Obviously there are pros and cons to any convention, but this is definitely one of the flaws with this design.

    Huh? Wouldn’t that be the case no matter what your class names are? If you have a bunch of things using one class name and you suddenly want half of them to look different than others, you’re going to have to do one of a few things:

    1. Change half the class name to some other class name.
    2. Add an additional class name to half the elements that defines the stylistic differences.
    3. Add some other, more specific selector to your CSS in order to select half the objects.

    Clearly, number three is best, but it’s not always possible (if there is no DOM pattern to the half you want to change). Number two is next-best, number one is worst.

    THis would be the case in any design convention I can think of. Wouldn’t it? Anytime you decide to change (or remove) styles from a subset of items that have previously been identical, you’re going to have to do one of these three. Using multiple classes doesn’t change that.

  37. 037 // Vladimir Carrer // 05.20.2009 // 4:25 PM

    How will be semantic css in Chinese or Italian? We should stop for all this semantic madness. I mean it’s ok to have common naming system this can be helpful if someone else should understand your code. There are lot of people telling me your CSS Frameworks are not semantic, without really understanding what is semantic and how should I call 12 column grid system? We don’t even have standard “semantic” naming system should I call it Logo or Header?

    Conclusion: If you have 2-3 columns site try to have give meaningful css names so if some else should modify your code will have more easy task, if you have more complex grid site try to make mini documentation about your naming system. And that is great about public CSS Frameworks they always have mini or maxi tutorial.

  38. 038 // Andrew Ingram // 05.20.2009 // 4:33 PM

    Using .alt as a hook for an alternative style was a bad example on my part, perhaps instead you would define a .message class and .warning, .error and .info.

    You could define .message to be a box with 20px padding and a 1px border and .warning, .error and .info would govern the background and border colours.

    I think my confusion came from you using presentational classnames in your examples and arguing against Andy Clarke et al whilst simultaneously making an argument that doesn’t really disagree with using purely semantic classes at all.

  39. 039 // craig zheng // 05.20.2009 // 4:33 PM

    Great post, Jeff, and delivered much sooner than promised ;) I’ve actually been putting some of these principles into practice in one of my current projects—Public Culture—and I’d worried that I might be overdoing it with classes as a result. Your argument eases that anxiety a bit. Nevertheless, you’ve encouraged me to revisit that code and continue searching for efficiencies. So thanks for that…

    Also, you might be interested to see that you were shouted out on the site :) Your last design for jeffcroft.com was inspirational during the design process…

  40. 040 // Kevin Pang // 05.20.2009 // 4:34 PM

    @Jeff

    The example I was thinking about would go something like this. Let’s say you have two types of boxes on your website, one for widgets and one for sporks. Let’s say that you initially want them both boxed and rounded so your divs would look like this:

    Widget
    Spork

    Now let’s say you change your mind and you want sporks to not be rounded anymore. Now you need to change all your spork divs to be

    Spork

    The alternative would be to already have two classes (which, as you pointed out in your post, will be very similar to one another violating DRY).

    Widget
    Spork

    Now, if you wanted to change all sporks to not be rounded anymore, it’s just a change in the CSS file instead of throughout your html.

  41. 041 // Kevin Pang // 05.20.2009 // 4:41 PM

    Damn, serves me right for not reading the warning. My HTML was stripped on my last post. Let me try again (Jeff, feel free to delete my previous comment):

    @Jeff

    The example I was thinking about would go something like this. Let’s say you have two types of boxes on your website, one for widgets and one for sporks. Let’s say that you initially want them both boxed and rounded so your divs would look like this:

    div class=”box rounded” Widget /div div class=”box rounded” Spork /div

    Now let’s say you change your mind and you want sporks to not be rounded anymore. Now you need to change all your spork divs to be

    div class=”box” Spork /div

    The alternative would be to already have two classes (which, as you pointed out in your post, will be very similar to one another violating DRY).

    div class=”widget” Widget /div div class=”spork” Spork /div

    Now, if you wanted to change all sporks to not be rounded anymore, you just need to change the “spork” class instead of all the spork divs throughout your html.

  42. 042 // Chris Eppstein // 05.20.2009 // 4:56 PM

    I guarantee everyone’s clients care way more about speed than semantics.

    Yes, but when developers started using javascript libraries and unobtrusive scripting and browser performance started to degrade, the browser makers responded by writing new, faster javascript engines that optimized the common case. Clearly a win for everyone concerned.

    Browser makers will adjust to the CSS best practices that we collective decide to use because performance is one of the best ways they can differentiate themselves. So I reject the choice between performance and maintainability except in extreme cases.

    Here’s a great writeup I found a while back on CSS performance.

  43. 043 // Jeff Croft // 05.20.2009 // 5:04 PM

    I think my confusion came from you using presentational classnames in your examples and arguing against Andy Clarke et al whilst simultaneously making an argument that doesn’t really disagree with using purely semantic classes at all.

    Fair point. My examples were shit, no doubt.

    @KevinPang:

    Okay, nmakes sense. But I think you may be misunderstanding me. I’m not AT ALL suggesting you should be using box and rounded instead of widget and spork. Definitely not! Widget and spork are clearly the better choices, here.

    So, using your example, it’d be more like this: all widgets have a consistent base look, and all sporks have a consistent base look. So these are each base classes. But maybe you have some widgets and some sporks that need dark backgrounds and some that need light. I’d advocate div class=”spork light”, in that case.

  44. 044 // Jeff Croft // 05.20.2009 // 5:12 PM

    So I reject the choice between performance and maintainability except in extreme cases.

    I generally do, too. It’s nice that this style makes your code a bit lighter, but that’s not why I do it. I do it because I find it way more maintainable.

  45. 045 // Luke Hutscal // 05.20.2009 // 5:16 PM

    I really like the ability to add multiple classes to elements in my markup, and I tend to take advantage of that by using descriptive classnames in an order that makes them almost read like sentences. A div for comments has the class “comment box”, while a list of links has the class “links list”.

    Being able to write rules to target each rule(and combination of rules) has helped cut down on a lot of repetition in my CSS.

  46. 046 // Kevin Pang // 05.20.2009 // 5:22 PM

    @Jeff

    It seems like you still have the same problem. What happens if you later decide you want those light sporks to not be light? You’d have to remove the “light” class from all your sporks, right?

  47. 047 // Anthony Bosio // 05.20.2009 // 5:31 PM

    As someone with one foot in both worlds (currently learning OOP with Python), I was blown away by Nicole’s presentation when I first saw it a couple months ago. In retrospect, I realize it is just the next logical step after using a CSS framework. I had recently completed a WordPress template using 960.gs and did feel a little dirty using all those classes. On the other hand, the speed in which I was able to create the template left me feeling pretty good.

    After watching the presentation, my co-worker wondered aloud if you would just end up with a class for every visual detail.

    People tend to want a cut-and-dry answer. One way or the other. Black or white. (With us or against us.) I guess the important thing is to strike a balance that works for the project at hand.

  48. 048 // Jeff Croft // 05.20.2009 // 5:37 PM

    People tend to want a cut-and-dry answer. One way or the other. Black or white. (With us or against us.) I guess the important thing is to strike a balance that works for the project at hand.

    Exactly. Please tell this to Kevin Pang. :)

  49. 049 // Scott G // 05.20.2009 // 5:51 PM

    I kind of like this idea, not exactly the same application but I multiple classes a lot, I would just like to come up with more clear conventions on how to use them across our industry.

    Some people discover them and just start applying them with all sorts of names and a kind of 50/50 weight to each class, where if you remove one you can bust the whole layout and each is so dependent on each other that you might as well just stick to variations of class names in your CSS. (hmm, make sense?)

    I figure multiple classes have to be quite simple as you stated above.

    eg. .m-round = round corners on a div .m-red = background colour red

    … then you leave the heavy lifting to the ‘core’ class or id of the HTML element.

    Also, I use the m- prefix to dictate it’s a multiple class and it’s not doing any major formatting. Meaning, if you remove a multiple class it shouldn’t wreck anything.

    Good post.

  50. 050 // Kevin Pang // 05.20.2009 // 5:52 PM

    @Jeff

    To be fair, I did point out that there were pros and cons to any convention. I never said (and I hope I didn’t imply) that what you’re proposing here is a bad idea. In fact, I like it on many levels (simpler css files, less repetition). But that doesn’t change the fact that it does have its drawbacks. It’s important for people to know both the pros and cons so they can make an educated decision on how to proceed. I’m not sure how my comments implied that I wanted a cut-and-dry answer, but if they did I apologize as that was not my intention.

  51. 051 // Jeff Croft // 05.20.2009 // 6:41 PM

    @Kevin Pang:

    I was totally teasing with that last comment. Hope you didn’t take offense! My bad. :)

    I agree with you completely — pros and cons, absolutely. For me personally, the pros of this outweigh the cons. But, like you said, everyone needs to make their own educated decisions! Sorry for the little joke. :)

  52. 052 // Todd Parker // 05.20.2009 // 6:59 PM

    This is a really great thread and this approach makes a ton of sense when you really need to come up with CSS that is flexible and modular. After a lot of experimentation, we ended up going with a “stackable” set of css classes in the jQuery UI CSS framework to make theming (and ThemeRoller) possible.

    We’ve had to defend the need for multiple classes on elements (aka classitis) but it seems like people really like this approach once they get their heads around it because it is so much clearer to understand and work with. Each little class only does one clear thing and isn’t a mismash of random rules that are hard to maintain as they interact with other rules.

    The coolest part of using generic classes that are named according to their purpose is that anyone can grab these classes and apply them to their projects so it makes the CSS originally intended to skin a small set of jQuery UI widgets truly portable across the web — lot of people have used these classes for custom plugins or even static websites which is really cool: http://jqueryui.com/docs/Theming…

    That is the real power of this approach. More details here on the class system we’re using if anyone is interested: http://jqueryui.com/docs/Theming….

  53. 053 // Jos Hirth // 05.20.2009 // 7:10 PM

    .rounded

    The .rounded example is interesting insofar as using something like that isn’t necessarily good or bad. Fortunately the difference between proper and improper usage of non-generic pimp classes is crystal clear:

    If they only occur in templates (and if there are only a few templates at most) it’s perfectly fine to use them. If you need to add/change/remove/rename them, you’ll know where to look and it will only take you a few minutes at most.

    Don’t put them into modules/components or your content. Don’t put them into any places which require hunting. Checking the settings of 100+ components? Not gonna happen.

    Surprisingly simple, isn’t it? :)

    OOCSS

    I watched Nicole’s presentations a while ago and the concepts are very interesting and effective. However, I think the name is somewhat misleading and it also seems to drive the attention into the wrong direction.

    The big selling point is the reversal of the whole process. Instead of writing CSS to make some markup look OK, you define a set of “legos” (a unified look for a specific markup structure).

    So, basically you create a style API whose “functions” can be invoked from any position on the page. The result are simpler and fewer selectors, no special cases, a consistent look out of the box, far higher productivity, a less steeper learning curve, and surprisingly compact CSS files.

    But “Object Orientated” doesn’t really describe this decoupled relationship between the markup and the styling. I mean… there basically is only this list of bricks (right after reset, layout, and base) and it’s a use it or die (or ask for a new one) affair.

    I guess I’d call it “Component-based CSS”, but for getting popular it needs a name which sounds as least as cool as “Ajax”.

  54. 054 // YHVH // 05.20.2009 // 7:21 PM

    Christ this was boring.

  55. 055 // John Faulds // 05.20.2009 // 8:21 PM

    I’ve been doing pretty much the same as the approach you’re advocating. And while I try to use semantic class names as much as possible, what do you do when handed a design that has a variety of different coloured boxes (apart from curse the designer quietly under your breath)? Calling them box1, box2, box3 isn’t really going to help you or anyone else when it comes to site maintenance, whereas yellow, green & blue is.

    And FWIW, I didn’t think classitis referred to the use of multiple classes per element, but rather the overuse of classes in general when you could use selectors in your CSS more smartly to achieve the same effect.

  56. 056 // Eddie Welker // 05.20.2009 // 10:01 PM

    It’s a really useful technique, yes, but I’m surprised how it seems to be taking everyone by surprise… especially with the wealth of JavaScript projects where adding/removing from the list of attributed classes is what you’re predominantly doing. Just seems like the logical “next step” in my mind. But hey, if Nicole, you, and others can promote it, all the better.

    I am looking forward to a time when a few people come to a consensus about a set of base styles, and start publishing them in the style of resets, or even better yet, libraries as exist in JavaScript. Because of the nature of CSS, it would be easy to discard what you don’t use for efficiency.

    For the record, I am against CSS variables… but I would be greatly interested using this technique as a basis arguing for the ability to work with multi-level inheritance in CSS. Then you’d begin to achieve some truly amazing things… as well as potentially making it easier for non-experts to use (given they have an adequate library to start with).

  57. 057 // Jeff Triplett // 05.20.2009 // 11:53 PM

    The problem with trying to apply OOP concepts into CSS is that they do not apply. I don’t disagree with what you’re saying from a DRY perspective but there is a huge fundamental difference between cascading and OOP. What you seem to be suggesting in terms of multiple class names being used is very modular.

    Tools like SASS / CleverCSS / etc help build a better foundation for a real CSS “framework”. If opening up a command line and typing in “compass —watch” is too hard for designers then this speaks of a bigger fundamental problem. Most of the designers that I know of (including you Mr. Croft) are very capable developers. For the generation that call themselves “founders” that refuse to learn new tools then they will be left behind. Most designer hybrids that I know all work on Rails / Django / insert buzzword or framework here projects and at least know how to invoke a shell and write simple apps.

    Regardless of my rant of the Zeldman-generation (seriously, no disrespect intended), CSS frameworks have to work outside the constraints of CSS in order to be useful. Blueprint, 960gs, YUI, etc do a good job of standardizing common constraints in CSS (typography, cross-browser compatibilities, browser style resets, layouts, etc) but even they can’t address problems that a true framework should be able to address.

  58. 058 // Jeff Croft // 05.21.2009 // 2:08 AM

    It’s a really useful technique, yes, but I’m surprised how it seems to be taking everyone by surprise… especially with the wealth of JavaScript projects where adding/removing from the list of attributed classes is what you’re predominantly doing.

    Yes, this is definitely not revolutionary stuff — not trying to claim it is, either!

    I don’t disagree with what you’re saying from a DRY perspective but there is a huge fundamental difference between cascading and OOP.

    Agree completely. I haven’t ever, and would never, call this “object oriented CSS.” Rather, it’s trying your best to apply some object-oriented concepts where realy object orientation doesn’t apply.

    I also agree with you about people unwilling to learn new tricks eventually fading away. Glad I’m not one of those people. :)

  59. 059 // Virginia Web Design // 05.21.2009 // 3 AM

    Thanks for the article. Anything that makes coding more efficient is a big plus in my book!

  60. 060 // Razvan Pavel // 05.21.2009 // 3:44 AM

    I myself work as this as well. i find it easier to have some general classes that control certain elements instead of having stuff like box-rounded-wide.

  61. 061 // Jeremy Keith // 05.21.2009 // 5:06 AM

    This word, classitis. I do not think it means what you think it means. ;-)

    Here’s what I’ve always understood by the term:

    Suppose you have five list items and each one of them has a class of “nav-item”. That’s classitis. The solution is to just put one class (like “nav”) on the list itself.

    So, as I understand it, the injunction not to use too many classes is more like, “don’t put classes on a bunch of elements if you can just put a single class on the containing element.”

    As for having multiple space-separated classes on elements, I’ve always found that to be one of the greatest semantic features of HTML. The way that this feature can be used by CSS in an object-oriented-esque kind of way is a great knock-on effect.

    The examples of “success message” and “error message” are perfect. I’ve used those (or something very similar) as very handy hooks for conditional CSS and JavaScript.

  62. 062 // Beth // 05.21.2009 // 5:36 AM

    Use a class name over and over or redeclare the same properties over and over? Seems obvious which should win out, but I think we’re often naturally hesitant to reuse any one thing too much in our markup because we’ve always been told it’s bad.

    The timing of your post is impecable, because I was just struggling with the same thing in a redesign I’m working on but now I feel vindicated :) Example: .entry, .entry + .review, .entry + .review + .music or .entry + .review + .book.

  63. 063 // Anthony Bosio // 05.21.2009 // 6:13 AM

    Just to be clear, my “some people” comment wasn’t directed at anyone in the comments. I really just meant our colleagues in general. Heck, I’ll confess to wishing things were that easy.

  64. 064 // Bill Kelley // 05.21.2009 // 6:23 AM

    As a rule thumb I don’t generally post to blogs, but I would like to say that I am quite impressed with the way this article has been written. I learned a few key things. They are:

    1. Multiple class ids on a single element are frowned upon. Personally this does not make a bit of difference to me. I am a programmers, as well a designer, a bit of a rarity. I believe that redundancy of code is bad. Short sweet code saves me time, headache, and booze (jk).

    2. Presentational class names are bad. This is a new one to me. I often give my classes names based upon what they look like. I find it descriptive enough to follow, but I do also like your examples of some semantic naming. I’ll have to give this some thought.

    3. People are working on programming or scripting languages that will work extensively with CSS. I say it is about darned time. I look forward to it, although I know I am the exception.

  65. 065 // Chris Wallace // 05.21.2009 // 6:47 AM

    Apparently I’m a bit late to the discussion. Three points to take away from this article:

    1. Write less CSS.
    2. Use descriptive (but still semantically rich, when possible) class names that are easy to understand.
    3. Jeremy Keith and Andy Clarke will kill you in your sleep for using .red10ptverdana.
  66. 066 // Jeff W. // 05.21.2009 // 9:07 AM

    I understand where you are coming from here but I think your advice is somewhat misguided.

    First off, principles like DRY and code reuse are not exactly object-oriented programming concepts. These are design philosophies that transcend all programming paradigms. These philosophies existed (although maybe under different names) before object-oriented programing existed and they continue to exist in languages that do not support the object-oriented paradigm.

    Object-oriented programming was conceived in a time when programming techniques like modular programming were already pretty widespread and were already placing great emphasis on code-reusability. So the advent of object-oriented programming contributed more to the ideas of data hiding, encapsulation, and abstraction than to the ideas of reusability. That’s not to say that reusability isn’t emphasized in object-oriented programming, but rather that using the object-oriented programming paradigm as a metaphor for reusability is sort of incorrect.

    And while inheritance is a core concept of object-oriented programming, it is also a core concept of cascading style sheets. So calling something object-oriented because it takes advantage of inheritance is also a stretch. The one similarity I see between object-oriented inheritance and cascading style sheet inheritance is that they both share a similar caveat: overusing inheritance is bad.

    For starters, we have to realize that inheritance is an innately limiting construct. Every step in the inheritance tree limits the reusability of our classes and increases the complexity of our system. Go too far with this and we end up with what is known as the Yo-yo problem:

    In computer science, the yo-yo problem is an anti-pattern that occurs when a programmer has to read and understand a program whose inheritance graph is so long and complicated that the programmer has to keep flipping between many different class definitions in order to follow the control flow of the program. It often happens in object-oriented programming. The term comes from comparing the bouncing attention of the programmer to the up-down movement of a toy yo-yo. Taenzer, Ganti, and Podar described the problem by name, explaining: “Often we get the feeling of riding a yoyo when we try to understand one these [sic] message trees.” [1]

    Most practices of object-oriented programming recommend keeping the inheritance graph as shallow as possible, in part to avoid this problem. The use of composition instead of inheritance is also strongly preferred, although this still requires that a programmer keep multiple class definitions in mind at once.

    More generally, the yo-yo problem can also refer to any situation where a person must keep flipping between different sources of information in order to understand a concept. See Design Patterns, Chapter 1 summary, for additional information.

    .

    As a general rule, most programmers understand that we should only subclass when you have an “is-a” relationship. For example, a circle may logically be a subclass of shape, but a red circle should not be a subclass of red. We think of red as a “has-a”, not an “is-a”, relationship. The “Box > Rounded > Wide” demonstration is good example of a bad inheritance hierarchy . My mattress and my skateboard are both rounded boxes but I don’t think they would naturally extend the same base class if I were to model them in a software project. The same concept holds true for CSS.

    By grouping things that are unrelated by their physical representation at the current moment in time, you undermine the entire purpose of using classes in combination with an external stylesheet. Now if you want to change the style of only a portion of your boxes you not only have to create new classes in your CSS file but you must also drop into all of your HTML files and modify your class attribute on every single box you want to change. This certainly isn’t conforming to the principles of DRY.

    So when you question the reason for not using presentational class names, this is your answer. Using class names like ‘class=”tleft”’ to represent something with left text alignment is just as DRY as using ‘style=”text-align:left”’. A better approach is to markup you html first with useful hooks for CSS by means of ID’s and classes that model purpose rather than presentational representation. This way when a designer has to make a modification in the future and they see ‘class=”user_message”’ they know they can open up a CSS file and edit the .user_message styles. This is in stark contrast to finding ‘class=”box rounded wide”’ and realizing they not only have to create new classes but also find every instance of this type of box in the entire project and add a new class to it. This can be a particularly complicated task when completely unrelated elements have the exact same class attributes but aren’t even related to the type of boxes that need to be changed.

    This isn’t to say I’m against the ‘class=”message error”’ example. I think that is a good example of using purpose to create hooks for CSS. If a designer wants to change the style of error messages, he simply changes the error message styles in the style sheet. He doesn’t have to worry about discerning which classes need to change in all of his HTML files. But again, this is less Objected-oriented and more just using CSS in the way it was designed to be used. And while this technique is exactly how I think CSS is meant to be used, I’m not sure that it supports any of the arguments you’ve made in your post.

    In the end, DRY doesn’t necessarily mean refactor ever piece of repeated code into it’s own self-contained class. If we did that we’d end up with classes like .width_140px. We should be less concerned about duplication in our css and more concerned about not wasting our time typing the same things over and over again. Code-generators, build tools, and scripting languages are all options to help overcome this hurdle while still keeping your styles clearly defined and our HTML easily maintainable. If you ask me, this would be a foundation for a full revision of the PRO CSS book rather than a revision based on breaking all the good rules that have been preached by all of the “puritans” in the past.

  67. 067 // Scott Phelps // 05.21.2009 // 9:17 AM

    A simple tip told with a short story.

    Sitting behind a sound board or mixer, either in a studio or live setting, there is a simple trick.

    In order to balance the sound or to find something in the mix, you don’t turn it up, you turn other things down.

    I try to apply this with design and CSS.

    Also, you can wear your ass as a hat.

  68. 068 // Colin // 05.21.2009 // 3:12 PM

    I came to comment and then saw that Jeff W. #66 said everything I needed to say and better.

    I really wish people would stop advocating non-semantic css because it’s “easier.” Sure it’s easier to build initially but then try to hand that off to another front-end developer that is told to redesign the page without touching the HTML.

    I’ve had projects like this before. When the code is non-semantic I have to sit there digging around and see what I can do and what I can’t and then it ends up with a bunch of ugly css — ie. #rightnav is now specified as float:left, and #redbox is now green, etc.

    However, when the html is well formed and with sensible semantic css hooks, then my job is easy.

  69. 069 // Chris Wallace // 05.21.2009 // 9:39 PM

    Yeah, comment #66 was awesome. If that guy has a blog, I’m going to replace one of the crappy blogs in my feed reader with that guy’s.

  70. 070 // Jason // 05.22.2009 // 12:13 AM

    Great post, but it’s going to take some time read through the comments.

  71. 071 // M. Bradley // 05.22.2009 // 8:26 AM

    Yeah, #66 illustrates the difference between signal and noise with a kick to the balls. Done. Convo’s over. Every body go back to tweeting in the blogosphere until the next round of entertainment.

  72. 072 // Horatio Goldstein // 05.22.2009 // 11:23 PM

    Haha, yeah, #66 should be the blog post — not the idiotic diatribe posted by Croft. I wish there were some peer review system in place for “experts,” because damn, how the curtain would fall.

  73. 073 // DAZ // 05.24.2009 // 4:28 AM

    I have an idea to add inheritance to CSS. Just add a ‘inherit’ property. That way you can build up a library of abstract classes and apply those styles to any element you want. For example:

    In library.css

    .rounded{ // some styles for rounded corners} .box{ // some generic styles for a box}

    In main.css have:

    .news-item { inherit: .rounded, .box; // more specific styles here }

    Then anything with a news-item class would ‘inherit’ all the styles from the rounded and box classes. This helps to get round the semantics argument as nothing would ever actually get a class name of ‘rounded’, they would just inherit its properties. If you don’t want rounded corners any more, just remove .rounded from the inherit declaration.

    This seems like it would be very easy to do and would allow abstract frameworks and libraries to be developed. It would also allow a good deal of repetition to be avoided and let designers focus on the unique elemnents of their CSS rather than constantly repeating themselves.

    Could this work?

  74. 074 // DAZ // 05.24.2009 // 4:48 AM

    I think the original post raises some good points and the comments have also raised some excellent points also.

    Thank you to Jeff W for a brilliant explanation on what OOP is all about (I had initially thought that what Jeff C was talking about wasn’t actually OOP, but thought the main argument about less repetition through using multiple classes was definitely worthwile).

    I liked the example of a red circle and the whole ‘is a’ and ‘has a’ definitions. I think this is why Ruby has modules, they are for the ‘has a’ definitions.

    An example of this could be a tank. A tank ‘is a’ vehicle, so the tank class would be a sub-class of the vehicle class. A tank ‘has a’ gun, so you would create a ‘gun’ module and this would be mixed in to the tank class.

    CSS should definitely be looking to go more modular with less repetition. At the moment this is being held up by IE6 not understanding chained classes like red.circle and there not being any way to inherit from another CSS class.

    One more thing - a few people have pointed out that the ‘rounded’ class would have to be removed from every element in the html if things changed in the future. Surely these boxes would have been created using an html-snippet (partials in Rails, not sure for other languages/frameworks) for these boxes anyway, so it would only be changed in one place?

  75. 075 // taelor // 05.24.2009 // 12:38 PM

    Loved the post. I’m a rails developer that just doesn’t get that whole design thing, but I would totally love to. Really thought, I write shitty CSS. But I think now after reading this post and the comments(#66), I might try to do a little bit better.

    But, I don’t get the whole IE6 issue, because I sure don’t waste my development time on that. Its much more efficient to message the user, “Hey, please upgrade to IE7 or preferably try: Chrome, Firefox, Opera, etc.” Same goes with javascript for me.

  76. 076 // Michael // 05.24.2009 // 4:41 PM

    I definitely think the new example with the “message” class works better. I actually did that exact method with a web app’s messaging system.

    The big problem with the original rounded box example is actually the same as what you claim is a good aspect - maintainability. The problem arises when you, or, usually the case, your client/boss, changes their mind and wants box A to not be rounded anymore and to have some new background on it. So now, you have to create a new class for the new Box A styling, AND THEN you have to go to every instance of <div id=”boxA”> in your HTML and change the classes you’ve dumped on to it.

    When you do the “traditional” method of styling, div#boxA and div#boxB, etc. would have their own styling and could be grouped if they shared properties (then perhaps with individual properties of their own - hence “cascading”). Then when something changes you can just go to the properties of that element and make the changes in one spot.

    This was a very interesting article though. I’m a traditional programmer and so I’m very familiar with OOP, but I’ve never really thought of CSS in terms of OOP.

  77. 077 // Jonathan Stark // 05.25.2009 // 1:31 PM

    Great post! I have to admit that I didn’t have time to read all two million comments, so I apologize if I am echoing someone… ;-)

    I just want to chime in with a common situation where presentational class names are bad (i.e. not some fake “ivory tower bad” - I’m talking “actual pain in the ass” bad).

    I build a lot of web apps that are specifically designed to be displayed in both desktop browsers and Mobile Safari on iPhone. Typically, the two versions render the same content in radically different ways; so much so that I usually write two style sheets and present one or the other by sniffing the user agent in the PHP.

    When you consider this situation, I suppose it’s obvious why giving a DIV a class name like “rounded” is a awful idea, but I’ll point it out anyway - the DIV probably won’t be rounded in both cases.

    As mashups, widgets, and third party non-browser apps proliferate, I find myself authoring my HTML docs more like they are an XML API. I then layer the presentational logic on top of it. Whenever I do get lazy and add some presentational info to the HTML itself, I always end up regretting it later.

    My $.02 - Cheers!

  78. 078 // Silviu Postavaru // 05.30.2009 // 10:10 AM

    I think that font end developers should know Javascript. SASS is a breeze compared to it. It also solves all the problems enumerated and will give you clean code that can be refactored and reused across projects. I know these solutions are still young and aren’t mainstream, but there is no excuse in not trying them out.

    If you are a font end developer please don’t pull out the “that is not my job” card as it is the road to mediocrity. I guarantee that if you start working with SASS you will be happier!

  79. 079 // Tim // 06.11.2009 // 10:59 AM

    Forgive me if someone brought this up already - I don’t have time to read all of the comments right now, but I’d like to touch on the success/error message example used at the end of the post.

    Why is it better to add multiple classes, than to simple write CSS that applies to all your messages, such as:

    .success,.error,.info { padding: 10px; font-weight: bold; }

    Then apply colors/background/border as such:

    .success { background: #eee; color: green; }

    Isn’t that essentially the POINT of CSS?

    I guess you save a few letters by only applying the first set of CSS rules to a class such as “message” but you lose those when you apply additioanl classes to the html element anyways.

    Now, having said that, let me point out that I have used multiple classes numerous times. And your post doesn’t strike me as a bad idea at all. This particularly comes up when working with certain CMS’s (Drupal comes to mind, definitely).

  80. 080 // Vitaly Babiy // 06.12.2009 // 11:38 AM

    Jeff great post, never looked at css from the OOP point of view. Next project I am going to give this approach a try.

    Thanks

  81. 081 // Ryan Atkinson // 06.13.2009 // 8:45 AM

    I don’t think the term “classitis” applies here. I’ve always taken that to mean unnecessarily applying classes to child elements that could just as easily be referenced from your css by targeting the parent’s class or id. This adds extra (unsemantic) that can be avoided by refining your html and css.

    Adding multiple classes (especially when they’re generated from backend code - CMS, etc) is genius. The most difficult challenge when developing a CMS is allowing for every exception/preference/mistake your end users can throw at you. By adding classes under certain conditions, you’re actually promoting the main purpose of css.

    For example, some pages may exclude a side column, but CSS doesn’t (and shouldn’t) allow you to test this condition. You will still have your div with id=”content”, but you can add a class “standalone-content” (or whatever… that name kind of stinks :P) when “#secondary-content” is absent. Most of your CSS will still be attached to #content, but the width/positioning/border may change when it’s the only content in the main area. And then you can target its children by starting with the class name.

    In the case of error/success messages presented by Tim above, the first line of CSS (padding, font-weight) could just be applied to .info (or whatever you want to call a “response message”). Then you add the 2nd class of .error or .success to change the color/background or other message-type-specific properties.

    Class names like “wide”, “round”, and any others that just describe what the element looks like are as bad as “font13pxblackbold”. But you can accomplish the same with “standard-container”, “highlight”, “info”, etc., and still keep the “puritans” happy :)

  82. 082 // gaus surahman // 06.13.2009 // 3:47 PM

    Never heard of OOP on CSS before. But talking about multiple classes and reusability of the CSS codes, I think I did it by nature, so did everyone. I started my first valuable project, a newspaper site, with a lot of elements. Finding out that I could not rely on a bunch of IDs for very similar elements, I ended up coding with multiple classes. It did save me line of codes and lot of time as well for maintenance. Glad that finally you did not disagree with that. Isn’t that in the spirit of jquery, the write less do more anyhow?

  83. 083 // CreativeNotice // 08.24.2009 // 8:51 AM

    Perfect. Thanks for the thoughts on this I totally enjoyed some sanity in the “semantic” css debates!

  84. 084 // Ian // 08.26.2009 // 10:17 PM

    Thought you might like this

    http://www.ooeygui.net/articles/431

  85. 085 // Jamie Web // 09.30.2009 // 1:40 AM

    I found this article an interesting read. I have never looked into applying OOP concepts to my CSS. Thanks for the great post.

  86. 086 // Moritz Wegmann // 11.24.2009 // 9:01 AM

    OOP is a good thing. So you can save yourself a lot of work.

  87. 087 // apangophork // 01.09.2010 // 3:54 PM

    Where is a good place to sale my old wrecked car? Please help me by sugesting some sites or companies.

  88. 088 // festmények // 01.12.2010 // 4 PM

    Great post, but it’s going to take some time read through the comments.

  89. 089 // useful tips // 01.19.2010 // 8:13 AM

    ah at last, I could find your article once again. You have few [url=http://tipswift.com]useful tips[/url] for my school project. Now, I won’t forget to bookmark it. :)

  90. 090 // web design glasgow // 01.19.2010 // 11:26 AM

    for css info you should check out theme forest, or net tuts they are some great info there

  91. 091 // Vintage // 02.18.2010 // 9:25 AM

    Any concrete specs on how to write CSS for best site loading times? I’m aware creating too many classes and repeating code causes longer loading times as the browser needs to load more code. I’ve heard something about browsers read code form right to left instead of left to right. Does this dramatically affect the way CSS is/should be written?

Tags for this entry
Links in this entry