An Introduction To Object Oriented CSS (OOCSS)

Advertisement

Have you ever heard the phrase “Content is King”? Being a Web developer, and therefore having a job that’s often linked to content creation, it’s likely you have. It’s a fairly overused but true statement about what draws visitors to a site.

From a Web developer’s perspective, however, some may argue that speed is king1. More and more, I’m starting to favour that stance. In recent years many experienced front-end engineers have offered their suggestions2 on how we can improve the user experience by means of some performance best3 practices4.

Unfortunately, CSS seems to get somewhat overlooked in this area while many developers (for good reason) focus largely on JavaScript performance and other areas5.

In this post, I’ll deal with this often overlooked area by introducing you to the concept of object oriented CSS and how it can help improve both the performance and maintainability of your Web pages.

The Principles Of OOCSS Link

As with any object-based coding method, the purpose of OOCSS is to encourage code reuse and, ultimately, faster and more efficient stylesheets that are easier to add to and maintain.

OOCSS

As described on the OOCSS GitHub repo’s Wiki page6, OOCSS is based on two main principles.

Separation of Structure From Skin Link

Almost every element on a styled Web page has different visual features (i.e. “skins”) that are repeated in different contexts. Think of a website’s branding — the colors, subtle uses of gradients, or visible borders. On the other hand, other generally invisible features (i.e. “structure”) are likewise repeated.

When these different features are abstracted into class-based modules, they become reusable and can be applied to any element and have the same basic result. Let’s compare some before and after code so you can see what I’m talking about.

Before applying OOCSS principles, you might have CSS that looks like this:

#button {
	width: 200px;
	height: 50px;
	padding: 10px;
	border: solid 1px #ccc;
	background: linear-gradient(#ccc, #222);
	box-shadow: rgba(0, 0, 0, .5) 2px 2px 5px;
}

#box {
	width: 400px;
	overflow: hidden;
	border: solid 1px #ccc;
	background: linear-gradient(#ccc, #222);
	box-shadow: rgba(0, 0, 0, .5) 2px 2px 5px;
}

#widget {
	width: 500px;
	min-height: 200px;
	overflow: auto;
	border: solid 1px #ccc;
	background: linear-gradient(#ccc, #222);
	box-shadow: rgba(0, 0, 0, .5) 2px 2px 5px;
}

The three elements above have styles that are unique to each, and they’re applied with the non-reusable ID selector to define the styles. But they also have a number of styles in common. The common styles might exist for branding purposes or consistency of design.

With a little bit of planning and forethought, we can abstract the common styles so the CSS would end up instead like this:

.button {
	width: 200px;
	height: 50px;
}

.box {
	width: 400px;
	overflow: hidden;
}

.widget {
	width: 500px;
	min-height: 200px;
	overflow: auto;
}

.skin {
	border: solid 1px #ccc;
	background: linear-gradient(#ccc, #222);
	box-shadow: rgba(0, 0, 0, .5) 2px 2px 5px;
}

Now all the elements are using classes, the common styles are combined into a reusable “skin” and nothing is unnecessarily repeated. We just need to apply the “skin” class to all the elements and the result will be the same as what the first example would produce, except with less code and a possiblity for further reuse.

Separation of Containers and Content Link

The second principle described on the OOCSS GitHub wiki page is the separation of containers from their content. To illustrate why this is important, take the following CSS:

#sidebar h3 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: .8em;
	line-height: 1;
	color: #777;
	text-shadow: rgba(0, 0, 0, .3) 3px 3px 6px;
}

These styles will apply to any third-level headings that are children of the #sidebar element. But what if we want to apply the exact same styles to third-level headings that appear in the footer, with the exception of a different font size and a modified text shadow?

Then we would need to do something like this:

#sidebar h3, #footer h3 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 2em;
	line-height: 1;
	color: #777;
	text-shadow: rgba(0, 0, 0, .3) 3px 3px 6px;
}

#footer h3 {
	font-size: 1.5em;
	text-shadow: rgba(0, 0, 0, .3) 2px 2px 4px;
}

Or we might end up with something worse:

#sidebar h3 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 2em;
	line-height: 1;
	color: #777;
	text-shadow: rgba(0, 0, 0, .3) 3px 3px 6px;
}

/* other styles here.... */

#footer h3 {
	font-family: Arial, Helvetica, sans-serif;
	font-size: 1.5em;
	line-height: 1;
	color: #777;
	text-shadow: rgba(0, 0, 0, .3) 2px 2px 4px;
}

Now we’re unnecessarily duplicating styles, and might not realize it (or simply don’t care). With OOCSS, we’re encouraged to give more forethought to what is common among different elements, then separate those common features into modules, or objects, that can be reused anywhere.

The styles that are declared using the descendant selector in those above examples are not reusable, because they are dependent on a particular container (in this case either the sidebar or the footer).

When we use OOCSS’s class-based module building, we ensure that our styles are not dependent on any containing element. This means they can then be reused anywhere in the document, regardless of structural context.

A Real-World Example Link

To further illustrate how OOCSS can be used, I’ll use something similar to what I did on my site’s recent redesign7. After coding the inner header element on my site, I realized that the basic structural styles for the inside of the header could be reused on other elements on the page.

So here’s something along the lines of what I had when I started styling my header:

.header-inside {
	width: 980px;
	height: 260px;
	padding: 20px;
	margin: 0 auto;
	position: relative;
	overflow: hidden;
}

A few of the styles listed here are unique to the .header-inside element. But the rest can form a module that I can reuse. So I can abstract the structural styles into their own reusable class. Here’s the result:

.globalwidth {
	width: 980px;
	margin: 0 auto;
	position: relative;
	padding-left: 20px;
	padding-right: 20px;
	overflow: hidden;
}

.header-inside {
	padding-top: 20px;
	padding-bottom: 20px;
	height: 260px;
}

The styles belonging to the .globalwidth class cover the following:

  • A fixed width
  • Centering using margin: auto
  • Relative positioning to create a positioning context for child elements
  • Left and right padding of 20px
  • Overflow set to “hidden” for clearfixing

Now we’re free to use these styles on any elements that require these same characteristics by simply adding that class to the desired element — without writing a single extra line of CSS.

For my site, I reused these structural styles on the primary content element and the inner footer element. Depending on the design, these styles could also apply to a horizontal navigation element that might appear between the header and the content, or any other element that has a fixed-width and needs to be centered on the page.

After adding the “globalwidth” styles to these elements, the markup would look something like this:

<header>
	<div class="header-inside globalwidth">
	</div>
</header>

<div class="main globalwidth">
</div>

<footer>
	<div class="footer-inside globalwidth">
	</div>
</footer>

Some may feel that this type of styles abstraction clutters the HTML and goes against the principle of separating markup from presentation.

But putting aside any debates about how this might affect the markup, no one can question that this abstraction has now made it easier to track down and modify the common styles that are used to structure these three elements.

The Media Object Link

One of the pioneers of the OOCSS movement is Nicole Sullivan158. She’s created a reusable module called the media object9 which, as she explains, can save hundreds of lines of code10.

OOCSS

The media object is a great example of the power of OOCSS because it can contain a media element of any size with content to its right. Although many of the styles that apply to the content inside of it — and even the size of the media element itself — could change, the media object itself has common base styles that help avoid needless repetition.

The Benefits Of OOCSS Link

I’ve already alluded to some of the benefits of OOCSS. Here I’ll expand on these.

Faster Websites Link

The performance benefits of OOCSS should be fairly clear. If you have fewer styles that are repeated in your CSS, then this will lead to smaller file sizes and thus faster downloading of those resources.

It’s true that markup will be more cluttered and thus create larger HTML files. But in many cases the amount of loss in markup performance will be greatly surpassed by the amount of gain in stylesheet performance.

Another concept to keep in mind is something that the OOCSS wiki refers to as performance freebies. This refers to the fact that every time you reuse something in your CSS, you’re essentially creating new styled elements with zero lines of CSS code. For large, high-traffic projects, these “freebies” could be a crucial performance gain11.

Maintainable Stylesheets Link

With OOCSS, instead of a constantly growing stylesheet full of specificity wars, you’ll have an easy to maintain set of modules where the natural cascade plays an important role.

When making additions to an existing site, you won’t be adding new styles to the bottom of your stylesheet without regard for what came before. Instead you’ll be reusing existing styles and extending your styles based on existing rule sets.

With this type of forethought, it’s possible to create entire pages while coding very little CSS. Any existing CSS modules can serve as a basis for all new pages, and any new CSS will be minimal. In some cases you might even be able to create a new fully-styled page without coding a single line of CSS.

These maintainability benefits also extend to the robustness of your stylesheets. Because the styles are modular, pages built on OOCSS will be less likely to break when a new developer starts to use the stylesheet.

Points Worth Noting Link

OOCSS has created a great deal of discussion in the community, raising some controversies. Here I’ll try to dispel a couple of common misconceptions.

You Can Still Use IDs Link

If you decide to work exclusively in an OOCSS manner, then your styles will be based largely on CSS classes, and you won’t be styling elements using the ID selector.

Because of this, many have falsely claimed that OOCSS encourages dropping the use of IDs completely. But this is not true.

The rule to avoid IDs is, more specifically, don’t use IDs in selectors. So it’s perfectly acceptable to use OOCSS principles (and thus avoid styling using the ID selector) while using IDs in your HTML for JavaScript hooks and fragment identifiers.

Of course, you may have a situation where you already have an ID applied to an element that you know is unique to the page. So, you can save a few bytes by avoiding adding a class to that element and instead style it using an ID selector. But even in this instance, it’s much safer to rely on a class to ensure you don’t run into specificity problems in the future.

Dealing With Smaller Projects Link

For smaller sites and apps, you could certainly make the case that OOCSS would be overkill. So don’t take this article as an advocacy for OOCSS in all circumstances — it will vary depending on the project.

Nonetheless, I think it’s a good idea, at the very least, to start thinking in terms of OOCSS in all your projects. Once you get the hang of it, I’m sure you’ll find it much easier to get it working on bigger projects where the benefits would be more noticeable and relevant.

Some Guidelines For Implementation Link

Getting started working with OOCSS could take time. I’m still working on it, so I don’t claim to have all the answers and experience in this area.

But here are some things you might want to start doing to help you get into an OOCSS mode of thinking:

  • Avoid the descendent selector (i.e. don’t use .sidebar h3)
  • Avoid IDs as styling hooks
  • Avoid attaching classes to elements in your stylesheet (i.e. don’t do div.header or h1.title)
  • Except in some rare cases, avoid using !important
  • Use CSS Lint12 to check your CSS (and know that it has options and method to its madness13)
  • Use CSS grids14

There will obviously be times when some of these rules will be broken, but overall, these are good habits to develop and will lead to stylesheets that are smaller and easier to maintain.

Follow Nicole Sullivan’s Work Link

If you want to continue learning about OOCSS, the most important person in the industry to keep up with is Nicole Sullivan158.

In addition to posting articles regularly on OOCSS on her blog, Nicole has done a number of presentations with accompanying slideshows. Below are some that you might want to check out:

Conclusion Link

Many people fear the OOCSS ideology because it seems to go against many of the so-called “best practices” we’ve learned. But once the long-term benefits of using OOCSS are understood, I’m sure many developers will become converts.

Overall I think OOCSS has a bright future in CSS development, and it’s a concept that all developers should start incorporating into their projects — at least on some level — to help create Web pages that are faster, more efficient, and easier to maintain.

(il)

Footnotes Link

  1. 1 http://www.stevesouders.com/blog/2009/10/06/business-impact-of-high-performance/
  2. 2 http://www.stevesouders.com/blog/
  3. 3 http://www.amazon.com/High-Performance-Web-Sites-Essential/dp/0596529309
  4. 4 http://www.amazon.com/Even-Faster-Web-Sites-Performance/dp/0596522304/
  5. 5 http://developer.yahoo.com/performance/rules.html
  6. 6 https://github.com/stubbornella/oocss/wiki
  7. 7 http://www.impressivewebs.com/rolled-new-design/
  8. 8 http://www.stubbornella.org/
  9. 9 https://github.com/stubbornella/oocss/wiki/Content
  10. 10 http://www.stubbornella.org/content/2010/06/25/the-media-object-saves-hundreds-of-lines-of-code/
  11. 11 http://www.svennerberg.com/2008/12/page-load-times-vs-conversion-rates/
  12. 12 http://csslint.net/
  13. 13 https://github.com/stubbornella/csslint/wiki/Rules
  14. 14 http://www.stubbornella.org/content/2011/01/22/grids-improve-site-performance/
  15. 15 http://www.stubbornella.org/
  16. 16 http://www.slideshare.net/stubbornella/object-oriented-css
  17. 17 http://developer.yahoo.com/blogs/ydn/posts/2009/03/website_and_webapp_performance/
  18. 18 http://www.slideshare.net/stubbornella/our-best-practices-are-killing-us
  19. 19 http://www.slideshare.net/stubbornella/css-bloat

↑ Back to top Tweet itShare on Facebook

Louis Lazaris is a freelance web developer and author based in Toronto, Canada. He blogs about front-end code on Impressive Webs and curates Web Tools Weekly, a weekly newsletter for front-end developers.

Advertisement
  1. 1

    I’ve been using OOCSS techniques for over a year on large projects with multiple front-end developers & back-end developers.

    The CSS produced is far easily managed as OOCSS forces a structure. When developers are working on the same project they can check what’s already been created and reuse that styling, and/or add an additive class to make the variation they need.

    I’ve also noticed benefits when the back-end developers can quickly add some CSS classes to elements and have a page 90% complete when page structures are similar.

    0
  2. 2

    Though the concept of better organization of CSS is tried and true, there is no need to add yet ANOTHER acronym to an already over-saturated market. I know everyone wants to coin the next term, but this is kind of out of hand.

    OOP-ing an object usually only makes it more understandable to developers and not designers. There are a myriad of concepts that are perceivable by both which can lead to cleaner, more optimized CSS without the need to associate it with traditional OOP methodology.

    1
  3. 3

    Its really handy m8..thanks for sharing :)…now i think in OOCSS perspective while creating stylesheets…kudos for your big mind to share such a good article.

    1
  4. 4

    On one hand, web developers don’t really have a problem with CSS classes poluting an element as long as they don’t have to do it. Look at all the UI frameworks (eg: jquery UI); to have a tabbed box you have about 4 classes added to the container, nativation and content holders. But that happens behind the scene and doesn’t count, right? :)

    On the other hand, unless you work on an environment like yahoo it’s hard to imagine having the need to organize your html and css that rigorously and adding a few extra elements “just in case” . Most developers are part of small teams, project varies enough not to start thinking about abstracting the css.

    I can see why this topic polarizes the audience so much.

    1
  5. 5

    Though it’s being an interesting attempt in order to fight bloated and unmaintainable CSS, I don’t think OOCSS is a ready-to-use solution. It demands much to complicated naming convention and raises a need for an enterprise-grade assets management system – because after a half-year development you’re going to be exactly as lost in multiple styles and their derivations as before.

    0
    • 6

      Oocss is a good thing to learn as a web designer i think may be its not ready to use but it worthy to be used in my opinion

      0
  6. 7

    In general, you bring up some good points in this article but to a certain extent.
    I believe it really comes down to the amount of re-usable code. Id selectors for css are slightly faster than class selectors… In other words, if ripping apart a couple of id’s css to share between lets say a few classes may actually be slower to render and potentially make your file size larger after adding the necessary classes/html. It all comes down to how much can actually be re-used between elements.
    Also keep in mind that for the very few people that still need to support IE6, IE6 does have issues with multiple class selectors for elements.

    0
    • 8

      @Brandon Actually IE6 supports multiple classes just fine (separated by a space, which is how they are used in the OOCSS framework). What it doesn’t support is “class chaining” (i.e: .class1.class2).
      Also IDs are not proven to be much faster than classes..

      0
      • 9

        @Rick, yes IE6 does support multiple classes… I said it has issues. OOCSS will generate more classes for elements at all levels, there is a potential of parent/child class selectors that may need to be selected. To fix the issue, an easy solution is to use the parent’s id selector… sort of breaks the idea a bit of using classes as your main selector. It is a potential issue that people may run into for IE6.

        IDs are proven to be faster (although minimal). Your source proves it (though I wouldn’t use them as a credible source). As browsers continue to improve efficiency, it will continue to be less of an issue.

        Basically what I am saying, its a judgement call for certain scenarios… and if you are lucky enough to support IE6, you should be aware of potential issues arising by utilizing just OOCSS as a solution.

        0
        • 10

          ID will always be (on average) faster than class lookups since the node tree search exits as soon as it finds the ID (could be near the root) – with class lookups with entire tree must be walked since there could be an instance of the class both at the root and in the leaves. It’s not a bad or good thing, just that ID’s and Classes are there for different reasons and a different algorithm is used appropriately.

          0
        • 11

          If you still support IE6 you have much bigger problem (beyond the scope of coding) than classes issues ;)

          0
      • 12

        I believe IE6 supports extending 2 classes, just not over 2 classes… so class=”class1 class2″ works, but not class=”class1 class2 class3″ … Can someone else confirm this, I remember checking this about 2 years ago while doing this on a huge site and have forgot about it since then.

        0
        • 13

          IE6 supports as many classes as you need. You can have ten classes on it, if you need, provided you’re not using class chaining in your style sheet. In the second example provided below, only the last class which is chained is honored (.c3). One of the ideas of OOCSS is to start with a base class and add on to it with separate rules.

          e.g.

          class=”c1 c2 c3″

          Works in IE6:

          .c1 { … }
          .c2 { … }
          .c2 { … }

          Does not work in IE6:

          .c1.c3 { … }
          .c2.c3 { … }

          More info: http://reference.sitepoint.com/css/classselector

          0
    • 14

      From what I understand, the speed benefit of the ID selector vs. the class selector is very small. But yes, it is a benefit, so that’s something to keep in mind. But, if the module abstraction saves you hundreds of lines of code, then the benefits easily outweigh the drawbacks.

      Also, IE6 does not have issues with multiple classes. IE6 has no problem whatsoever with multiple classes declared on an element — as long as the selector that targets the classes uses a single class.

      The problem you’re referring to is when IE6 bugs out due to the use of chained classes in your CSS selector. So you can’t do this in IE6:

      .one.two.three {
      /* notice no space between the classes */
      }

      So as long as you aren’t chaining your classes, there is no problem using multiple classes on a single element in your HTML.

      More on the IE6 chained classes bug here.

      0
    • 15

      The amount savings in download time would likely be greater than time saved from the browser parsing the css classes as browsers are pretty fast at parsing most selectors.

      0
      • 16

        Don’t forget about selector search speed through js/DOM. Selecting by class is substantially slower than selecting elements by id. Taking out ids in favor of classes will ultimately result in a slow page (if your page has lots of js element manipulation).

        0
        • 17

          You would also have to consider how you are utilizing the js to select an item by class. Each id on the page should be unique; you should not have 2 ‘#widget’ on the page. So for multiple elements that you are looking to interact through js/DOM the ‘.widget’ class would be the only way to go.

          0
    • 18

      I tend to agree with you, Brandon. However, I’d like to emphasize the performance aspect. I think the performance hit of using classes instead of unique ids, can be significant (if used too liberally). Ideally you only use css classes for “base”/”outer” elements that are not used often, and then use ids for specific styles and let cascading take care of the rest.

      0
  7. 20

    Nice way of organizing styles, I’ve been doing it for a while now, the only issue with this is the use of non semantical css naming conventions such as “header-inside”. I just hate it when I see this type of css naming on a project I’m working on.

    CSS classes should not represent position, but what they represent.

    0
    • 21

      Gunnar Bittersmann

      December 13, 2011 3:17 am

      “CSS classes should not represent position, but what they represent.”

      You said the right thing, but with a wrong term. There are no “CSS classes”. Classes are a construct of the markup (HTML) to classify elements – by “what they represent”, right.

      Later(!) classified elements can by styled using CSS’s class selectors.

      This OOCSS approach turns this upside down and (mis)uses classes for how elements are presentet. No good thing, IMHO.

      1
  8. 22

    One of the reasons I don’t get behind methodologies like OOCSS or many CSS frameworks is because they’ve completely abandoned the thought of semantics in markup. Your markup, which includes your class names, is meant to describe the content without thought to the how the page will be styled. By littering your markup with classes like “globalwidth” or “skin” that lack any semantic meaning, you’re just cluttering your markup.

    I do find that there are occasions where using this approach is a viable solution (for example, I used it when creating rapid prototypes for testing that would never actually be released as production code), but I have a hard time encouraging the use of this technique in actual production.

    0
    • 23

      I completely understand what you’re saying about “semantics” (and what others have said). But really, what it boils down to is that we want our code decisions to actually solve problems.

      Although it feels “clean” to keep content and styles separate, in many cases it is not a benefit. Code should solve problems. OOCSS solves problems related to performance and maintainability. Overly pedantic “semantics”, solve very few, if any, problems.

      I don’t necessarily think everyone should use OOCSS. If you think it can solve some CSS problems for you, then use it. If you think it creates more problems than it solves, then don’t use it. Or else use a pre-processor (as someone else pointed out). Whatever benefits your code.

      But I do think it’s good for all developers to understand the concepts of OOCSS, which is why I wrote this piece. :)

      0
      • 24

        I would love your input regarding a brand new CSS framework I released last week.

        Cascade Framework is fully OOCSS, which makes it far more modular and flexible than any other CSS framework out there. In spite of being very feature rich, it has a very tiny footprint of between 2,5Kb and 10Kb minified and gzipped, depending on which features you want.

        You can check it out at http://jslegers.github.com/cascadeframework/ .

        1
    • 25

      classes like “globalwidth” and “skin” _are_ semantic – just not content-semantic. They’re style-semantic. And, since CSS is for styling, that’s how it should be.

      Having said that, I don’t really like having five to fifteen classes on any particular element, which is something this “OO” approach can lead to quite easily.

      0
      • 26

        I believe the objection here was not that non-semantic code was in use in CSS, but that those classes appear in the markup, which, in my estimation anyway, is there for content structure. The idea is to keep style references out of the markup.

        1
    • 27

      Css has nothing to do with content semantics. I use classes like .i1, .i2, .w10 – whatever – and also google will not rank you any better if you name your sidebar .sidebar or .sb – you will only save a few bytes since you use shorter class names. The only benefit of naming your header div .header (if you’re not using header tag) is that when another programer comes working after you he will not have to do a search for what this class is since the name is logic. HTML TAGS are meant for semantic MARKUP – not css classes.

      0
      • 28

        One) The benefit of semantic class names to future developers (this includes our future selves) should not be underestimated. Good class names don’t just explain the structural nature of the elements they are applied to but also indicate the reasoning behind the structure used and the relationship between disparate elements.

        Two) From the W3C HTML5 specification describing the use of the class attribute : “authors are encouraged to use values that describe the nature of the content, rather than values that describe the desired presentation of the content.”

        The opportunities for content – and the markup describing it – to become portable is increasing as technologies and methods of access change. I don’t think it is unreasonable to expect that trend to continue. This means that it is worthwhile for us to consider the need for our content to be available in a variety of contexts and forms.

        By focusing on and favoring semantics in both our choice of tags and class/id names we improve the flexibility of how our content can be presented across contexts. This doesn’t mean that there aren’t cases in which non-semantic class names provide a meaningful advantage but that should be the exception, not the rule.

        1
  9. 29

    There are some good points here, but with some I’d strongly disagree.

    First of all, what you suggest about dropping descendant selectors for the purpose of possible reusability of a style in other places, is no OOP at all – well, maybe it kinda is, but with global written all over it. What you’d end up with is dozens of pointless classes for the same elements depending on their looks – that doesn’t seem like a good approach to me.
    Yes, browsers read CSS selectors from right to left, so descendant selector are slower, but they resemble OOP classes much better.

    Secondly, as others already stated, you use lots of pointless classes that trash your HTML semantically. Maybe I’m old school, but I still put separating content from the looks at the top of my priority list.

    0
    • 30

      It’s true that “OOCSS” may be a misnomer, but that’s really beside the point.

      Also, you said:

      “What you’d end up with is dozens of pointless classes for the same elements depending on their looks”.

      If your elements look different, you’ll end up with “dozens of pointless” rule sets regardless of whether or not you use OOCSS. So I think you’re not understanding the benefit here. You’re only abstracting the styles that you’re intending to reuse, so instead of a dozen unique rule sets with repeated styles, you’ll have a dozen unique rule sets with no repeated styles.

      0
      • 31

        I get what you mean, but I don’t see why would you need several abstract classes for one element when you can achieve the same OOP-like inheritance by simply using selectors with different weights and rely on HTML structure instead of classes.
        Common properties land in declarations with lower weight, specific ones in further down the road. That’s how it has always been – I don’t see a point in changing it now.
        That way you reuse your styles like you want here, but still have semantically correct HTML.

        Only upside of using such class hierarchy is that your selectors will be faster for the browser to work with – I give you that.
        On the other hand, I’d imagine it would be much more difficult for other developers to step in in the middle of the project and catch up with your already elaborated syntax.

        0
  10. 32

    I would embrace the so-called OOCSS principles (you keep using “OO”; I do not think it means what you think it means) with a CSS preprocessor (LESS, for example), where you could pack recurrent styles as reusable declarations.

    However, using the class attribute to apply styles is a step back, as we are involving the document itself into managing its visuals, which is NOT what CSS is all about. An exception would be web apps which heavily rely on a componentized UI, and even then, skinning is solely the UI toolkit’s business (using separate stylesheets and dinamically generated HTML which the UI toolkit library provides and manages on its own).

    Documents where semantics matters should not need style-related stuff spoil its structure with that kind of hooks.

    0
    • 33

      While I agree with you in regards to using a preprocessor like LESS or SASS, I think you miss the performance side of his argument. While LESS and SASS make developing a lot easier, it does nothing for performance. LESS and SASS consolodate CSS style so that you would develop the css in a similar way as OOCSS, but the css that gets sent to the browser, is the same css as if you hadn’t organized it at all.

      0
  11. 34

    I tried this myself some time ago, and I think it doesnt really help. Tearing the styles of an object apart means you have to check different places later if you want to change something. I therefore rather “duplicate” some properties but have all the information in one place. The thematical fragmentation of CSS files can help even more.

    0
  12. 35

    I’ve been using this method and the one great thing about it is you have to think about your site in a global sense. Before using this, as soon as I had a design, I’d see the main containers and just start pounding out code. This usually lead to a lot of code getting repeated and added unnecessary code.

    With this approach, I take more time laying out this site, looking at the design and layout a lot more in depth. This allows me to find areas where I can re-use code and set those as the “prototype” classes and then add classes with the rest of the necessary styles (which is usually very little additional code).

    In short, it’s not only made my sites faster, but it’s made me a better, more thorough developer.

    0
  13. 36

    The only performance boost I read about in the article was by download. If that’s the case why not just argue for compression? As mentioned in the comments you can achieve a parsing speed boost too. Let’s see some benchmarks on the speed of the oocss vs non-oocss. Unless there is a real benefit there then you can take my original statement of arguing for compression and write an article about that.

    0
    • 37

      Compression will be done on top of an already OOCSS driven stylesheet. Do you really need benchmarks for whether or not a 900 line CSS file would download faster than a 1500 line CSS file? Because that’s pretty much what it boils down to.

      0
      • 38

        I don’t want a benchmark for download speed. I want a benchmark for execution time. Obviously the smaller file size is going to download faster. But, what’s the most efficient way to get the file to execute. If my 1500 lines executes 300ms faster than your 900 but takes only 200ms more to download….. well I think you see my point. All of this is unproven of course; which is why I’d like to see some tests.

        0
  14. 39

    It strikes me as interesting that “OOCSS”, as defined here, eliminates the use of descendant selectors, which I have used very successfully to namespace my styles.

    For example, in a web app, different parts of an interface may require different styling for similar elements. If I have <a> tags with the class name “button” in both the menu bar at the top of my app, and also in a sidebar menu (but with different styles), I would use “#menubar .button” and “#sidebar .button”. I may have a generic style for the “.button” class elsewhere, but I want special styling when a button is within a specific context.

    I have not run into any issues with this, but I would love to hear your take on this approach.

    0
    • 40

      So in that situation, with OOCSS, you could accomplish the same thing with something like this in your HTML:

      <button class="button-basic button-skin"></button>

      So this frees you up to use the added “skin” class on any button, no matter where it appears. Nevermind the class names I’m using, these are just illustrative.

      In a very large project, whatever “skin” you’re applying that makes the button slightly different in the sidebar will likely be used elsewhere too. So, this way, you don’t limit the use of that class to just within the sidebar. And if you need a different skin, just use a new class elsewhere.

      And yes, I understand that you like the readability of “#sidebar .button” in your stylesheet, but when you factor in the code savings, the potential specificity problems, and the potential for reusability, I think the benefits outweigh that small drawback of code readability.

      Really, with developer tools as powerful as they are to help track down styles, it shouldn’t be necessary to “namespace” your styles in that way. Plus, you can accomplish the exact same type of “namespacing” using good CSS comments.

      0
      • 41

        I see your point. If suddenly I decide that the button styling in my sidebar would be perfect for a modal dialog, and a feedback form, suddenly I’m duplicating code or adding more selectors to my CSS rules.

        When creating reusable widgets, I will write rules like this:


        .button { ... }
        .button.compact { ... }
        .button.icon { ... }
        .button.compact.icon{ ... }

        It’s similar, but instead of writing
        <a href="#" class="button button-compact button-icon button-compact-icon"></a>
        I can write
        <a href="#" class="button compact icon"></a>

        0
        • 42

          The only problem here is that you’re “chaining” the classes in your selectors. You don’t want to do that with OOCSS, because they’re still not reusable. And chaining doesn’t play nice with IE6 (if you need IE6 support).

          You want instead to have base objects (like .button) but then extend those objects with skins (like .compact or .icon). So the the “skins” could also apply to another element, not just .button.

          0
        • 43

          I use this technique too. I rarely need to support IE6 these days which now allows me to chain my elements and make smarter code. eg:

          <div class="wrapper"></div>
          <div class="narrow wrapper"></div>
          <div class="wide wrapper"></div>
          <div class="wide footer wrapper"></div>

          this allows me to setup various rules like:
          .wrapper{}
          .narrow.wrapper{}
          .wide.wrapper{}
          .wide.footer.wrapper{}

          0
  15. 44

    OOCSS can be unnecessary for smaller sites and teams so I can understand why most front end developers don’t feel the need adopt this method of CSS organization. However, the benefits are incredibly visible when it comes to large sites and large front end development teams.

    You can end up with 10+ different pieces of content with incredibly similar styles. Duplicating properties makes CSS files huge over time. Without documentation of CSS classes, the same properties get defined over and over. Overriding IDs become a specificity nightmare between front end developers. The gains become much more apparent in file size and with developers of different CSS skill levels. Don’t forget checking out http://smacss.com too.

    0
  16. 45

    I think most of us have used OOCSS for a while without actually declaring it as such. I think the hardest thing to do with this method is to keep consistent naming convention that is intuitive to multiple people and to have a well sectioned CSS file. Otherwise you end up with the very oposite of what OOCSS can provide, a bloated CSS file with redundant / overlapping style declarations.

    0
  17. 46

    OOCSS – what a big name for so little news.

    0
    • 47

      Max, I checked your post but didn’t see anything, did you forgot to include the link to the “big news” that you’ve come up with? You’ll have to forgive me if not, with a smart-assed reply like yours, I figured you would be following it up with something ground-breaking.

      If this is such old news, let us know why. Perhaps you can help the rest of us and the author better understand the topic in question. If your half as smart as you are rude, I’m sure we can all learn something from you. ;)

      0
  18. 48

    Gunnar Bittersmann

    December 12, 2011 1:10 pm

    “Don’t use presentational or behavioral markup” is the 2nd of Jens Meiert’s basic rules .

    But this OOCSS approach is just that: presentational markup. @class attributes just for the purpose of styling. It does not improve maintainability, quite contrary: On later style changes, you’ll end up changing @class attribute values in zillions of HTML documents instead of changing the code in just one file – the stylesheet.

    “If you have fewer styles that are repeated in your CSS, then this will lead to smaller file sizes and thus faster downloading of those resources” is not true. The compression algorithm (you serve your stylesheet gzipped, don’t you?) makes a file with repeated lines almost as tiny as a file with no repetitions.

    0
    • 49

      “On later style changes, you’ll end up changing @class attribute values in zillions of HTML documents instead of changing the code in just one file – the stylesheet.”

      Absolutely untrue. You’re thinking only of worst case scenarios, which would be a problem whether you use OOCSS or not.

      “The compression algorithm (you serve your stylesheet gzipped, don’t you?) makes a file with repeated lines almost as tiny as a file with no repetitions.”

      First, I’d like to see some proof of that because I highly doubt it’s true. Especially when we’re talking about hundreds of lines of CSS. Are you actually trying to say that 500 lines of CSS would not have an impact on a CSS file’s final compressed size?

      Also, this is not a matter of either/or. In other words, you gzip regardless of OOCSS, so if you also use OOCSS to save hundreds of lines of code, then you’re getting the best of both worlds. Your comment seems to imply that OOCSS doesn’t get gzipped…?

      So my advice is: Use OOCSS if it saves you significant amounts of code, and gzip your files regardless.

      0
      • 50

        But with your approach, what about the characters you need to add on the HTML part of the website, Louis? Those counts, too. Your CSS will end up quite bloated, and the HTML too, filled up with descriptive, redundant classes.

        I prefer leaving my HTML the purest as possible, describing the function, not the aesthetic, and styling it merely though the CSS side.

        But thanks for the article anyway. It gave me motivation for writing about a total different approach.

        0
        • 51

          As far as I can tell, the extra HTML is minimal but the potential for smaller and more maintainable CSS is very high. And “clean HTML” is, in my opinion, highly overrated. I may be addressing that topic another time. :)

          But yeah, I completely understand if people don’t like this approach. It’s not for everyone. But I do think the principles should be understood and applied at least on some level.

          0
      • 52

        Gunnar Bittersmann

        December 12, 2011 9:24 pm

        “Absolutely untrue. You’re thinking only of worst case scenarios, which would be a problem whether you use OOCSS or not.”

        No, it’s no problem when the markup was written not thinking about styling. Then you just change the stylesheet without touching the markup again.

        OOCSS and separation of content (HTML), presentaion (CSS) and behavior (JavaScript) are both optimizations – with different goals. I prefer the latter.

        “First, I’d like to see some proof of that because I highly doubt it’s true.”

        Why haven’t you tried? Well, I did. I took the Universal Declaration of Human Rights whose text takes 11017 bytes. Gzipped: 3915 bytes. Appending the same text again makes the uncompressed file twice as large, of course. Not the gzipped file, though, it takes only 4411 bytes. Another repetition: 33 kb become 4736 bytes. That’s how compression works.

        0
        • 53

          Interesting results. I did a test using an online tool and got different results. I tested my own CSS file, and it Gzipped from 35,000 bytes down to about 8,700. Then I doubled the size of the CSS file and the gzipped result was over 16,000 bytes.

          I’ll do some further tests, because this is definitely something worth looking into a little more deeply. Thanks.

          0
  19. 54

    Something is terribly wrong with this post. The way you structure and plan you CSS code has nothing to do with the Object Oriented Pattern. OOP is a pattern. It’s when you have a class model and can create new objects with it.

    This is terribly confusing.

    0
    • 55

      OOP != OOCSS.

      OOCSS is probably a misnomer (I didn’t coin the term, I’m just explaining the concept here). But generally speaking, all CSS developers understand that CSS is not programming, thus this should not cause any confusion to anyone who knows how CSS works.

      OOCSS helps you create reusable class-based modules that can be reused anywhere, and that can be extended with other classes. That’s the gist of it. There’s no need to compare OOCSS to OOP; that’s a topic for another post. :)

      Also, the word “object” is not an English word that’s reserved exclusively for object oriented programmers. It’s a word that means whatever a dictionary defines it as, so there’s no reason it can’t be used to describe a method to organize your CSS.

      0
    • 56

      Rajeev J Sebastian

      December 16, 2011 1:52 am

      OOP is a philosophy more than a set of features in languages or compilers. The focus of OOP is not classes: rather they are objects. It is the idea that many different individuals share common traits and therefore can be grouped/described/etc by a class or prototype; further, that classes and individuals themselves may be organized through (class and object) patterns such as aggregation, inheritance, mixin, delegation and so on; that individuals can communicate among each other also following patterns such as methods, messages, etc.

      Why can’t this be applied to CSS? My exposure to OOCSS itself is minimal, however I can see the appeal. Languages such as LessCSS, as well as new CSS3 features, allow to create such OO organizations with browser, compiler and language support. For e.g., using mixins. XBL binding is very clearly OO in nature.

      Multiple classes on a single element can be compared with inheritance (.button, .button.submit, .button.add.entry), and it is easy to see where the concept of “HTML/CSS class” originates.

      The addition and removal of classes on a given element triggers a “message” or “method”, which is utilized to implement CSS3 animations. I mean, that an addition or removal of a class, could trigger a “process” of change.

      The list goes on… I could argue that we already use OO concepts when writing HTML, CSS and JS. The only question is, how can languages, language extensions and frameworks help us formalize this. LessCSS and Mootools are very good examples for this.

      On the other hand, specific recommendations about what kind of class names to use, avoiding certain selector types are hard to accept. This OO formulation of CSS seems to me to be too simplistic.

      0
  20. 57

    This way you pollute your HTML with descriptive classes for the mere purpose of aesthetic reasons. Not a good idea. We should aim for a pure semantics in our HTML.

    It’s very possible to keep your CSS simple and ordered. Tools like LESS and Sass are there to be used. They are a good fun, too. And wouldn’t be brilliant to be able to style your HTML without having to change a comma in it, just via CSS?

    0
  21. 58

    The biggest problem I have with OOCSS is, like you say, the name. It’s a complete misnomer, which I’ve found is very polarizing, especially with devs familiar with OOP. A lot of front-end devs don’t really know what object-oriented even means unless they’re that mixture of front and back-end. But, you release something, ya gotta give it a name…

    What we’re talking about here is nothing more than the cascade, there is nothing new about this.

    Most front-end devs eventually start coding this way as they get more experience, they realize they can factor things out to more generic classes that can be applied to various elements.

    0
  22. 59

    You make some interesting points and I can see the potential benefits, I do however think that the concept would need to be employed carefully.

    If you took the concept to the Nth degree, you’d end up with .blue { color: blue } and .100px { width: 100px } (deliberatly trying to prove a point here) which would then end up with html with so many classes that your classes are almost as heavy ( filesize wise ) as adding the styles inline.

    I can see how having a generic ‘button’ class could be useful as it could be employed accross an application to give a consistent look and feel without adding more classes than you’d probably end up doing anyway.
    But on the flip side, the need to add new classes to the HTML when you choose to abstract a chunk of a your CSS and move it into a new class could be a major headache. Whilst originally if you have all your styles up front it should be ok if sensibly thought out, over time the refactoring could be painful.

    0
    • 60

      I agree. The abstraction level should be practical and usable. I would never encourage single-line “objects” or similar implementations.

      0
  23. 61

    I think I go one step further and make “styles” as an object…Ill have a .ds class for my drop shadow, .rc for rounded corners, .ts for text-shadow, etc…. and apply that when I want it….some things might get a drop shadow, some might get the rounded corners, some get both.

    So my code would read like class=”rc ds”

    0
    • 62

      That’s the way I’ve gone too. These sort of things should be consistent, along with things like a headline typeface, box/panel colours and border-widths etc.

      Within a large team, it also makes it easy to explain to content editors as well as CMS developers that DIV class=”lightblue rounded bordered” will display a light blue bordered box with rounded corners and stops them hardcoding inline styles…

      0
      • 63

        The Recusion King

        August 23, 2013 5:12 am

        That is absolutely the worst approach to take with CSS. You might as well be using Font tags. What exactly do you think is going to happen when your .lightBlue class has to change to yellow because the client wants it yellow now? You either 1) change the colour index in the lightBlue class, making its name utterly misleading or 2) change all of the HTML to a new yellow class, thereby creating a massive markup job across many pages.

        0
  24. 64

    Douglas Bonneville

    December 12, 2011 4:09 pm

    Do your best to be organized up front with as few classes and id’s as possible and then let entropy take over, since it’s going to happen no matter what. Long before the site gets unmanageable the site will be replaced by a redesign.

    Attempts at instilling high degrees of control to offsite natural site life degradation have a return-and diminish relationship between effort and return on effort.

    Say it takes ZERO thought to do your basic standard CSS site like you’ve done 1000x for the last 10 years. Right there is a good return on investment. No brain power, just the effort to type. Now try and introduce a forced “decay proof” method and you have to sell it to others, police it, remind others, practice it yourself. Then one day at midnight someone needs something now and the fastest way is to pop a style in the end of the style sheet. Back to bed, problem solved. Then you have too much to do the next day and you forget to “move” the style to the “right place” or implement the “right way”. So you let it sit. Then your coworker does the same. Boom, in 3-4 months, your effort and salesmanship are up in smoke. You lose some credibility.

    Easier: let your CSS grow naturally after doing a best effort initial setup and plan for it to get a bit tangled and eventually die a natural death when that site has lived its life.

    Keep Firebug handy and enjoy life.

    0
  25. 65

    Uncanny. I’ve been writing CSS for a decade and I’ve tried every system you can imagine. Only recently did I finally alight, by my own trial and error, on exactly this methodology. No descendant selectors, no ID selectors, no element-based selectors.

    Why so much wasted time and effort? Because I was in thrall to the doctrine of semantic CSS. It needs to be debunked. If you want truly semantic CSS you will waste lots and lots of time and your stylesheet will be unmanageable.

    I am an absolutist about semantic HTML but I’ve concluded that a compromise is in order for class names. Class names should not describe the exact visual appearance of the markup but it’s fine for them to describe its presentational role. This way you keep your sanity.

    0
  26. 66

    Douglas Bonneville

    December 12, 2011 4:19 pm

    “…your stylesheet will be unmanageable. ”

    Yes, reality always sets in! Therefore, why bother much? I don’t say why bother at all, but I do say why bother much? With a tool like Firebug your CSS just really doesn’t need to be all that organized. Again, yes, it should have SOME foundational organization because if you built your site right at the start it will naturally have some, so don’t worry about it. Organize it like a garden then let it go. 99% of time it just doesn’t matter, even on huge corporate sites.

    I’ve worked on so many “it just grew like this” sites with no rhyme or reason that I no longer pontificate or care about CSS this or that way. As long as it’s there and I can get at it with Firebug to find the line I need with a single key stroke, I’m golden. Most people are that way too.

    0
  27. 67

    This is an awesome article, without any doubt!!! For a web developer this is a Must read article.

    0
  28. 68

    Its very usefull for me. ya its great. superb

    0
  29. 69

    There are some good ideas in here and I praise the writer for writing the article about something that is different to the norm.

    But in practice this would be difficult to implement. As soon as sites get large, the maintenance for such a technique would be a nightmare. You would make a change to a class and it’s effects would be unknown. It could effect leaf pages that you didn’t know used the styles.

    It would also be difficult for new web developers to make changes to the site as they would need to know the structure of a lot of elements before making changes.

    Not only that but the examples are quite simplistic and don’t really show what a large scale CSS style sheet system would look like.

    This maybe a good technique for small websites or websites in which a single developer is working on, but for a large scale websites and for teams of developers, I would avoid such practices without having a set plan on how you will tackle the scalability of such a practice.

    This goes against encapsulation in which global elements are used as an easy way to make changes.

    0
  30. 70

    Mark Anthony Degamo

    December 13, 2011 12:21 am

    nice article…I just have some concerns on avoiding descendant selectors and not using IDs as styling hooks. I had somewhat alike implementation as OOCSS on my stylesheets, and I heavily rely on selector grouping because I don’t think assigning one class to many elements is not a good practice.

    Using your .global-width example, we could simply write our css like this:
    .global-width, /* your OOCSS class */
    #wrap-all, /* notice the ID selector */
    #nav,
    #nav ul, /* and descendant selector */
    .footer p /* even a child element */
    {
    width: 960px;
    }

    This way, we can have cleaner mark-up
    <div id="wrap-all">
    <div id="nav">
    <ul></ul>
    </div>
    <div class="global-width">
    </div>
    <div class="footer">
    <p></p>
    </div>
    </div>

    0
  31. 71

    Markup language cannot be object-oriented.

    0
    • 72

      Seconded! The heading made me smile. Web designers and developers should look at other industries and borrow techniques if it truly helps put things in perspective when it comes to the web. From proper scripting conventions to branding. If it works, why not? However, there’s a line to be drawn – CSS is in no way object orientated. In the least if it dealt with data and data structures I would then agree but it doesn’t.

      You can get away with object orientated design philosophy with CSS in relation to HTML in relation to PHP and construct your solution accordingly.

      0
    • 73

      OO is only a paradigm, it’s not the feature of some executable code. And CSS may have inharitance, polymorphism etc. So, CSS can be object-oriented.

      0
      • 74

        Agree. It would be correct to say…

        CSS is object-oriented markup language, but is **NOT** programming language (certainly, not OO programming language).

        0
      • 75

        CSS ironically does allow for “hierarchical relationships” (in a loose sense) but I’m not going to argue the fact that it can be OO. Simply put, it’s not capable of retaining cohesion between different identifiers or classes across multiple stylesheets let alone inline which the end result is a hierarchy that’s enforced and not by design.

        That’s why I stated that you can get a way with using the OO design philosophy (or OO paradigm) in order to model your CSS… then yes. The title should be An OO Design Approach with CSS.

        0
  32. 76

    I have been coding like this with css for a while now and I would recommend it any day. Not only does it speed up the end result (especially when you code your JavaScript properly too(no nasty plugins!!!)) it is also pretty useful when dealing with pesky clients who like to change their website a lot!

    0
  33. 77

    This is a really good introduction to OOCSS, I know I am guilty of using #sidebar h3, #footer h3 so I will be giving this a try, it’s tidy.

    Also there is a small typo in the html markup for the global width example, the footer tag opens with a header :)

    Thanks for this.

    0
  34. 79

    Actually, “you are doing it wrong”. In order for your approach to work you have to flood your HTML with layout-related classes. I repeat: LAYOUT-related classes. The whole point of using CSS is the separation of content and design. Ideally there should be not a single layout-related piece of code in your HTML.

    The better way to do proper CSS is by using SASS/LESS and make use of mixins, etc. This keeps your HTML semantic, clean and small and also allows you to write easily maintainable and reusable CSS code. Plus: If you got you’re HTML right you can add mobile stylesheets, print stylesheets, etc. in a jiffy. With the HTML tailored to your design the way you are promoting it this will most likely be harder and more work (and produce larger file sizes).

    0
    • 80

      “The whole point of using CSS is the separation of content and design. Ideally there should be not a single layout-related piece of code in your HTML.”

      So you *never* use classes on your HTML elements? You can’t make up a rule that’s impossible to obey. :)

      0
      • 81

        Gilles Vandenoostende

        December 14, 2011 2:49 am

        No, there’s a difference between using few, well-chosen and descriptive class-names to differentiate blocks of similar markup (i.e. an unordered list used for your site navigation should look different than when used inside a blog post, yet without classes there’d be no way to target them efficiently) and littering your entire markup with purely decorative classnames.

        It’s the difference between ul.navigation and ul.horizontal.full-width: one has meaning that is universal regardless of the site’s design, while the other one is tightly coupled to this iteration’s visual design, and should the design change the markup will have to follow suit (or you’ll risk going mad trying to make something with a class “.blue” look red, for instance).

        Tools like LESS and SASS that enable the use of “mix-ins” allow you to write all these re-usable css classes and use them without modifying your markup.

        So instead of having:

        <div id="header" class="full-width blue"></div>

        you can have your HTML thusly:

        <div id="header"></div>

        and inside your LESS/SASS:

        #header{
        .full-width;
        .blue;
        }

        0
      • 82

        Gilles pretty much said everything there is to say already. It’s not about not using classes, but about using them properly: Give them real meaning, use the classes to describe the content, not the visual appearance!

        I’m pretty sure when you started with CSS webdesign someone told you not to use classes like .red or .blue but rather name them .main, .aside, .important etc. The same is true for .inside, .globalwidth, etc. as you propose to use. This just is really bad coding style (sorry for having to say that) and makes everything actually harder to maintain than easier.

        When I look at someone else’s CSS and find some definitions like article { … }, #mainContent { … } then I know what it’s all about and where to find it. However if I encounter something like .globalwidth { … } then I really have to dig deep inside the HTML to figure out what you were trying to achieve with this.

        An even more important point: Let’s say we have to redesign this whole thing and the footer should now be smaller than the rest of the page. With your setup I either have to go inside the HTML to remove the .globalwidth class or in case I only have access to the CSS I have to get rid of all .globalwidth styles and restyle every element that used that style before. If the HTML/CSS was done the proper way you would just have to adjust the footer style, done.

        0
        • 83

          Honestly, when was the last time you redesigned an entire page and kept all the HTML exactly the same?

          That just doesn’t happen. It’s one of those theoretical benefits that never actually occurs.

          Also, with developer tools you should have no problem whatsoever finding out what “globalwidth” does.

          Finally, if you really want to make only the footer different, then you simply add a new class to the footer’s class attribute and style away. It’s that simple.

          I think people are complicating these suggestions because of their habit of only using so-called “semantic” classes and IDs.

          0
          • 84

            Well I have some example with rebrand. Our client changed his mind and wanted all cms boxes to have orange background in the header background and soft blue as a content background.

            Let’s imagine we are using pure OOCSS. So we can have for example these classes:

            “.module” “.blueaHeading” “.whiteContent”

            and this structure:

            <div class=”module blueHeading whiteCOntent”&gt;..

            Now we have to go to our css files and add new classes .’orangeHeading’ and ‘.softBlueContent’, after that we have to find all our CMS boxes in our code and give them proper classes instead of the old ones.

            Let’s imagine we are using SASS/COMPASS mixed with OOCSS principles.

            .myModuleIWanttoChange{
            @include module($blue,$white);
            }

            Now all we do is this..

            .myModuleIWanttoChange{
            @include generalModule($orange,$wsoftBlue);
            }

            0
          • 85

            Totally agree. I would never recommend people to use colors in their class names. That’s just asking for trouble. OOCSS does not encourage colors in class names.

            0
          • 86

            Louis, the fact that you can’t redesign something without changing the markup is HTML’s problem. It should be possible, but someone just left it rot in a dark corner. You should check the AXR Project

            0
        • 87

          I am styling huge platform where is a lot of objects like tables, subtables, forms, subforms, different CMS boxes. As you can imagine each of these object groups have it’s own css rules which can be applied to it’s objecst.

          But there are two big reasons why is really necessary to give proper semantic names to the classes (when styling huge platforms).

          a. possible rebrand
          b. re-using the platform for some other client

          So OOCSS yes but just with SASS/COMPASS, where you can define your classes with non-semantic names and put them into classes with semantic names.

          0
  35. 88

    Great post, but I can’t say that I agree with the idea 100% of pure OOCSS. IDs are the perfect solution for (say) wrappers with a particular context; they are faster to traverse (having higher specificity), and the OOCSS model can lead to markup bloat – you only have to look at the rendered markup of any typical Blogger or WordPress blog to see this.

    My biggest gripe about many posts like this is that models of this type (as well as layout frameworks) only work well for sites that vary little from page to page – notably blogs, portfolios, and relatively lightweight applications. Complex commercial websites and applications (such as the ones I work on) tend to be less bound by a ‘one-size-fits-all’ design and having less specificity leads to all manner of layout issues between contexts.

    Another horses for courses situation, and I would encourage everyone to investigate the best model / hybrid for their particular application.

    0
  36. 89

    I prefer use 2 technique:

    .button {…..}
    .box {…..}

    .sidebar {}
    .sidebar .box {….}
    .sidebar .box .button {…..}

    0
  37. 90

    This is almost just an introduction to CSS. Nothing here worth calling anything fancy other than CSS, and certainly not Object Oriented.

    0
  38. 91

    Oh, great. Another person creating another new term (this time OOCSS) to something that is not new at all. Or isn’t a “thing” at all.
    Almost 100% of redundancy here.

    0
  39. 92

    I found the article really useful, thanks!

    0
  40. 93

    Agree with the comments above. CSS declarations are NOT objects.

    Do not get me wrong, help is appreciate it, specialy for newcomers but you´re just confusing people (specially newcomers) with such naming for what, on the other hand, is nothing more than applying some comon sense to your stylesheets. This kind of class chaining it´s been doing for a veeeery long time on grid systems for example.

    Sometimes I feel like you guys are trying to reinvent the wheel with each new article. Relax.

    0
    • 94

      they are not trying to reinvent the wheel; it’s even worse.
      people create new terms and apply them to old stuff to sell books, tutorials, themes etc. I read a lot on the web and I’m pretty sure that 90% of all content related to webdesign, “ux” design (as if you could design a user experience) are redundant and misleading.

      0
  41. 95

    This to me is how writing CSS could work in a way that you can adjust styles very easily due to grouped declarations. The downside though is the need of multiple classes which are cluttering the html, putting styles back into the content-markup. Personally I prefer a method where you have fast and easy code by grouping declarations.

    Usually this means i have a couple of ‘chapters’ in my CSS-file:
    – @import (e.g. linked fonts)
    – reset (resetting some standard value’s)
    – colors (backgrounds, colors, shadows etc.)
    – typography (fonts-styles, -sizes etc.)
    – general (general sizes and positioning)
    – A chapter for each main content-section (header, sections, footer etc.)
    – animations

    This way everything is grouped, i can change values trough the entire site on a single location in a single file. Instead of using dozens of classes I put multiple selectors at each declaration. For instance if the links in the header should be red at :hover but in the content at all times I write:

    header#top a:hover, header#top a:focus,
    article a {
    color: red;
    }

    Hope this gives some insight and it can be helpful (and that I’ve used the right terms : )

    0
  42. 96

    I like how a lot of people in the comments are so quick to judge and assume that they don’t need to dive into css in an object oriented fashion or don’t care for the name. I think if you are doing any css in your field, front end or back end, you should really try this out if you have not. Ever since I have been writing css with proper inheritance, I have never looked back and all the good companies I have worked for and still work for utilize this method. I care about my work, and to me this is a way of engineering code and not just styling code.

    Also, I really like seeing people code there websites in a bunch of IDs because it makes its so much fun for me going into the code and adding more overrides to other overrides (because everything was scoped to the id) and adding to a mess that wasn’t planned out from the beginning. I’ve found the most efficient way for me and other people who dive into my code, is to create a base style (global styles), create a layout style, and then the page override css. (this can override layout or modular styles.) I think this is where a lot of confusion comes in with people complaining about OO styles is because sometimes its hard to determine when we should override, or should we just create a new class.

    When people use IDs and scope to that element to style: ex: #container1 a {color: #000;} will always override .container1 .class1 .class2 a {color: #000;}. Basically what I am saying is that when you start with IDs you will always have to scope to that ID, thus sometimes creating unnecessary chaining in your css code.

    Also, when someone is approaching this method in OO styling, doing div class=”one two” and in the css you are writing one.two {attribute: whatever},when I see this in code, I always assume are people overriding a class rather than combing the classes?

    I would just like to know how people go about structuring their style sheets in this OOCSS fashion. Its always interesting to me, because this is not really a one way street, it can be done in several ways, and that’s why css is so intriguing to me because I have been doing css/jquery/yui for many many years, and I am always learning new cool things. And I just get mad when people blow stuff off like this, because it is so amazing how much this helps other people in your team and not just yourself.

    0
  43. 97

    For all those who are making the argument that OOCSS ruins “semantic” markup, please read Nicole Sullivan’s notes, as compiled by Luke Wroblewski, from her talk this week at An Event Apart, San Francisco:

    http://www.lukew.com/ff/entry.asp?1469

    In particular the sections on “Extra Markup” and “Semantic Markup”.

    0
  44. 98

    The point of CSS is cascading styles.
    The power of CSS derivates from selectors.

    Any method deprivating the developer from the full array of techniques useables in CSS (from Ids to classes to child to adjacent to nth) is just stupid.

    Selling this method with a buzzword like “object oriented” is even worse.

    Period.

    0
    • 99

      Doug Crockford (in his presentations, books, and blog) promotes the use of certain aspects of JavaScript (i.e. “the good parts” of the language), while recommending certain “bad parts” of the language be avoided.

      Would you say that Crockford is “depriving the developer from the full array of techniques usable in Javascript”?

      0
  45. 100

    I just came off an enterprise project using OOCSS(it’s an just an approach to CSS and not a framework or anything new per se!) and there was a large backlash from it but after using it for so long I feel that it’s worth using and will use it again. If you’ve built with her classes you’ve undoubtedly used her line class and grids over and over or tailored your own which you’re totally open to doing… You’re the developer! I took out what I liked made a layout.css and I can throw together nice markup that lays out perfectly IE 5.5+ in no time. If your UX people know what’s up and design for development you have an efficient combination.

    I know it’s not “object-oriented” in the true sense of the word (i guess) and I don’t think anything thinks it’s supposed to be, bad use of language in the programming sphere and it’s a lot to wrap your mind around when you first see it, but I think it’s a good approach to developing CSS for large scale websites. I don’t think her git project is an “open box” solution or framework, rather, a collection of useful best-practices. Just check it out and see what she’s doing and see how it can be applied to how you’re writing code for your projects.

    There was a lot I didn’t like about it and I think if there was better documentation people would embrace it a little more. At the company I was with it was instructed to bolt it on by the original lead, but that’s not how it’s supposed to be used… although I definitely will use her .line class over and over. It works. “Separating structure from skin” is ideal and once you use it for awhile you write less CSS… alot less. Your layouts become very easy to work with and explain to people just coming in.

    I agree with a lot of what Ross said and I too am interested in how people deal with inheritance and their overrides in their css… especially in regards to writing OOCSS because like he said, there’s a lot of ways to skin a cat but together we can create a better way to scope projects from the beginning and have a lot more fun marking these projects up and owning it from the inside out. I’m a firm believer in starting your project from scratch and not using unnecessary frameworks, etc. Pretty much everything you’ll need to do has been done, so try and do it with the less code possible and leave room for growth and don’t box yourself into a corner.

    Anyone who uses OOCSS hit me up! I can hit the ground running with this stuff.

    0
    • 101

      I would love your input regarding a brand new CSS framework I released last week.

      Cascade Framework is fully OOCSS, which makes it far more modular and flexible than any other CSS framework out there. In spite of being very feature rich, it has a very tiny footprint of between 2,5Kb and 10Kb minified and gzipped, depending on which features you want.

      You can check it out at http://jslegers.github.com/cascadeframework/ .

      0
  46. 102

    As someone that works in a startup, speed trumps semantics when we are trying to get the product out to be verified and tested.

    Semantics is meaningless unless you get the product right and people buys it and uses it. Then you can start optimizing for accessibility and semantics.

    OOCSS makes a lot of sense in our situation, if it speeds things up to get the job done for prototyping things, why not?

    Also, I agree that by adopting OOCSS you exchange a slight drop of performance in exchange of a huge gain of CSS performance. Browsers today have little problems parsing HTML, but CSS is the next big thing that slows down browsers next to Javascript.

    In the end, if it helps Facebook and Yahoo increase the sites’ performance drastically by adopting OOCSS, why not? Not only it works better on the client side, it saved MASSIVE bandwidth because you’re not declaring styles again and again and again.

    0
  47. 103

    After reading some comments here, I think that the “OO” in “OOCSS” is largely misunderstood.

    Nicole’s “Object” in “OOCSS” means a single element on the page, e.g. a button, a news ticker, a date object, a column title etc.

    Instead of using a top-down approach (style the page first, then the column, then the element e.g. #about-us #sidebar .title, #page-header .slider .btn), we should use a bottom-up approach (style the element first, e.g. .small-title, .primary-btn) so that the element can be reused at any part of the page without any problems.

    Thus all elements that you created are an “object” which you can use every where else on the page. That is the idea of “object” in OOCSS, it is not exactly the same with the Object with OO programming.

    0
  48. 104

    Interesting read. I found the comments an interesting debate to read.

    In my opinion OOCSS has it’s pro’s and con’s. From my own experience OOCSS is useful when it comes to common elements such as pure CSS3 buttons, where we can adjust button colouring with the simple change of .btn.green to .btn.red. Things like that is great.

    But if we are styling major elements, i believe we should be using specific class names/id’s in this case. Just so they are not lost in reused naming conventions and the markup is kept simple and clean.

    0
  49. 105

    Ramesh Vishwakarma

    December 14, 2011 4:33 am

    I think this is the really a great way to implement the css. In this way we can reduce the size of our css file.

    -1
  50. 106

    I’m amazed there is such a debate in the comments on this. I thought everyone [competent] was doing this. I’m self/book taught, and I’ve been writing CSS like this for years, ever since the WC3 validator first flagged a warning on me for redundant CSS that could be better served by creating a single class for all those sharing the same styles.

    Honestly, when I started reading I was wondering why this article even needed to exist. I am normally well behind the curve for techniques, and this is old hat to me. I agree with the above poster that said this is just giving a new [and confusing] name to classic inheritance – and for no good reason.

    1

↑ Back to top