First Look: Object Oriented CSS

In October, I’ll speak at Web Directions South 2009 in Sydney about CSS Frameworks. One of the main questions I will answer in my talk is whether or not you should use a CSS Framework in any given project. Since the alternative is writing your own CSS styles from scratch, I’m researching some of the latest thinking on hand-coded CSS.

Object Oriented CSS for high performance web applications and sites

One prominent voice in this arena is Nicole Sullivan, who has developed a methodology called Object Oriented CSS (OOCSS). She outlined this approach to writing CSS at Web Directions North 2009, and the 48-minute video is available.

Sullivan is a talented and engaging presenter, but I found the video a lot to take in all at once. Since watching it, I have applied the principles of OOCSS to an internal project here at SitePoint, and I feel like I have a better grasp on what it’s all about.

A Change of Perspective

Just another framework? Think bigger: “OOCSS isn’t really a framework … but a way of writing scalable, sane, maintainable CSS,” writes Sullivan. Sullivan uses and recommends a grid framework like Yahoo!’s YUI Grids, but you’re free to write your layout styles from scratch using OOCSS principles if that’s your thing. But OOCSS applies equally to the work you do after you have implemented your site’s layout, as you design the blocks and content that slot into your layout.

Most web designers tend to write CSS code so that it requires as little extra markup (whether <div> or <span> tags or class attributes) as possible. Fundamentally, adopting OOCSS is making a mental shift towards easy maintenance and reuse of your styles, even if it means writing extra HTML markup.

OOCSS methodologies help you to look beyond your immediate design goals and organize your code so that adding new site content that reuses the same styles in the future becomes trivial. With OOCSS, adding a new type of page to your site should mean that there’s no need to create additional CSS styles or selectors. New page types should be able to reuse existing CSS styles as much as possible.

When designing a site with OOCSS, you must break your design into reusable components, which OOCSS calls objects. Each component is a fixed HTML structure, to which you apply a set of CSS rules that control its layout (in OOCSS parlance, the structure), and another set of CSS rules that control its appearance (the skin). That component can then contain arbitrary HTML content: paragraphs, lists, tables, and so on, all of which is styled independently of the container in which it appears.

This last point is crucial. Under OOCSS you must avoid what Sullivan calls “location-based selectors” — that is, styles that affect content differently, depending on the part of your site in which it appears. If you want, say, a list to look different in a particular part of your site, you should add a class attribute to it and apply the styles based on that attribute. This ensures that the list can be lifted out and reused elsewhere on the site, with its style remaining intact.

An Example in Code

Let’s say every page of your site had a sidebar, the code for which looked like this:

<div class="sidebar">
  …sidebar content…
</div>

Now, let’s say you had a set of pages where you wanted this sidebar styled a little differently — say with a different background color to highlight a sale on certain products. You would probably also want to make changes to some other elements of those pages because of this sale, too.

Traditionally, your approach to this might be to add a class to your page’s <body> tag:

<body class="onsale">

“Brilliant!”, you would think. “Now I can make all my style adjustments for this sale without making any further changes to my HTML code!” Then you would set about writing a bunch of style rules like this one:

body.onsale .sidebar {
  background-color: #FFA500;
}

The approach recommended by Object Oriented CSS is quite different. Instead of a single class applied to the body of your page, you would create a new class for each type of element that you wanted to change for the sale. Here’s what the sale style for the sidebar might look like:

.onsalesidebar {
  /* extends .sidebar */
  background-color: #FFA500;
}

This class is said to extend the existing class that describes the standard style for the element. You then apply it in addition to the existing (base) class:

<div class="sidebar onsalesidebar">
  …sidebar content…
</div>

Now, a content editor can confidently copy and paste this sidebar code into another page of your site, or even a brand new page, and know that it will be displayed with the same styles applied. The same principles apply to the styling of the content within this sidebar.

The guidelines for OOCSS actually recommend a considerably more complex HTML structure for reusable components like this, which enable more intricate styles to be applied to them — including rounded corners and border effects — but this simple example effectively demonstrates the fundamental principles behind OOCSS.

What’s the Point?

Sullivan works at Yahoo, where her primary focus is on improving web site performance. Aside from the copy-and-paste reusability of styled HTML content and component blocks, OOCSS claims to offer significant benefits in performance.

By prioritizing the reuse of CSS styles across your site, OOCSS results in considerably smaller CSS files, but slightly larger HTML files. This trade-off is desirable because the size of your CSS files directly influences the amount of time that the browser displays a blank page while your site loads. Smaller CSS means less time spent looking at a blank page. Once your CSS has loaded, your site’s HTML content is displayed progressively as it loads. The result of this trade-off, then, is greater perceived performance, even if the total load time is slightly longer.

Furthermore, by avoiding location-based selectors, you reduce the amount of work that the browser has to do to determine the actual appearance of any given element on the page. Especially on mobile browsers, but even on the desktop, this can produce significant performance gains.

Is It Worth It?

If you’re lucky enough to be the only front-end developer working on a project, you might like to take the OOCSS principles for a spin. Where the reusability benefits of OOCSS really shine, however, is when working in a team environment.

Senior front-end designers can define the reusable structures for the site. Visual designers can apply attractive CSS skins to those structures. Content editors can write the content that slots into those structures with confidence, knowing that only the styles they expect will be applied to the content they write.

Coaxing an entire team to jump aboard the OOCSS bandwagon can be a significant undertaking, however, and that’s the point I’m at here at SitePoint. Having applied OOCSS principles to a little project on my own, I now have to decide if it’s worth bringing this to the SitePoint design team.

What do you think? Are the benefits of OOCSS worth the extra discipline required to adopt it, or is CSS complicated enough already?

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://www.genexbs.com Genexbs

    Very interesting, we always thoughts about building object oriented CSS for large scale portals. To us it looks very logical to do so as it will help in long term basis when we need to modify styles of the portal keeping consistency. I am glad sitepoint highlighted object oriented CSS. We hope to get some time soon to experiment on obj css.

  • digitaldanuk

    Sorry, but this is not object orientation…. where are the class definitions (and I mean the object classes, not the .onsalesidebar, class=’blah’ etc), where are the objects? IMHO the fundamentals of OO can never be applied to a CSS environment… An OO solution to web design would be one that combines all elements of web design: javascript, CSS and HTML, where the objects being the elements on the page. Each object would have its own methods for how it is displayed (CSS) and how it functions (Javascript)…. In other words, if web design were to be truly OO’d then the following simple HTML page:

    <html>
    <head>
    <style>
    p.myclass
    {
    font-size:50px;
    }
    </style>
    </head>
    <body>
    <p class="myclass" id="myid" onclick="alert('Hello World!')">Hello World</p>
    </body>
    </html>
    

    Could be mapped to the following simple classes and object instantiations:

    
    class HTMLElement
    {
    public function HTMLElement() {}
    public function Output() {}
    }
    class HTML extends HTMLElement
    {
    Body body;
    public function HTML() {}
    public function SetBody(Body b)
    public function GetBody() { return this.body; } 
    {
    this.body = b;
    }
    }
    
    class Body extends HTMLElement
    {
     HTMLElement[] elements = new HTMLElement[];
    public function Body() {}
    public function AddElement(HTMLElement el)
    {
    this.elements.add(el);
    }
    public function Output()
    {
    // go through each of the elements calling their Display function
    for(i=0;i<this.elements.length;i++) this.elements[i].Output();
    }
    }
    
    class P extends HTMLElement
    {
    string text;
    int fontsize;
    // more other properties that might govern the look and feel of the P
    public function P(string text)
    {
    this.text = text;
    }
    public function Click()
    {
    // something to make an alert! .e.g. system.alert(this.text);
    }
    public function Display()
    {
    // something to output the element while applying all the spec in this object
    }
    public function SetFontSize(int pixels)
    {
    this.fontsize = pixels;
    }
    }
    
    HTML myHTMLDocument = new HTML();
    Body myBody = new Body();
    P myP = new P("Hello World!");
    mybody.AddElement(myP);
    myHTMLDocument.setBody(myBody);
    myHTMLDocument.GetBody().Output();
    

    I think I prefer the way is is already… … or ASP.NET.. :)

  • digitaldanuk

    by the way, im not an ASP.NET developer…

  • Damien

    Yeah, what he said!

  • Ants

    Hi Dan UK, while it may not be object oriented coding where the object is a chunk of digital information in the machine conforming to the classical definition of an “object”, it is object orientation as far as the even more abstract concept of object “information” is concerned i.e. the virtual object in your head and not the object in the machine. Sorry if that hurts your fragile little mind!

  • jonathanstark

    Hi all –

    I’ve been hearing about so-called “OOCSS” more and more and thought I’d chime in with an “against” for those who might identify with my situation.

    In my case, I build web apps. Most of them are specifically meant to be viewed in both desktop and mobile browsers. The differences between these two devices are extreme enough that I usually have separate style sheets for each. The two design versions often bear very little resemblance to each other. Adding lots of design specific class names to my HMTL might make it much easier to program one version of the site, but it would make it much tougher to program the other.

    I do admit that my opinion is based on the specific nature of my work and that so-called “OOCSS” could be a useful for someone. My work is pretty utilitarian and therefore, I don’t have thousands of lines of CSS to manage. At any rate, I won’t be adopting this approach.

    Cheers,
    j

    P.S. FWIW – Using “object oriented” as the name for this approach is a real head scratcher; there’s nothing OO about it.

  • nathj07

    I like this idea of chaining the CSS classes. However, I must say this is not OO in the strictest sense, it is simply taking some of the ideas of OO and applying them neatly to CSS. For example the idea of inheritance is not properly represented here but it does enable some very nice re-use and so it really is in the spirit of OO.

    I am now moving out of CSS development (job change) but will be keeping an eye on this for future developments and for use on future large projects.

  • Martin Adelstein

    Well. As its seems, it is not what I would call OOP either – However the inheritance factor is something which existed before, but was not used in a programmatic way and obviously to its full extent. The OO in OOCSS is IMHO the focus on inheritance taken from REAL programming languages.

    I applaude the use of common sense in CSS design here. It is brilliant as it provides extendibility and maintainability.:)
    But to call that OOCSS is something like the attempt to generate a buzzword which simply doesn’t really belong here.

    It is a mere way of taking basic inheritance a step further and a different approach to organize css isn’t it ?

    Cheers,
    Martin

    http://www.the-set.com

  • Mattijs Bliek

    Isn’t this about the same principle as Jason Santa Maria suggested a while ago in his article about Modular Layout Systems on 24Ways?

    http://24ways.org/2008/making-modular-layout-systems

    He finds better use for it as well in my opinion.

  • Phil

    I wholeheartedly agree that this isn’t OO coding. It is one of the fundamentals of the cascading aspect of stylesheets though and anyone developing websites should have an understanding of this.

    This is basic CSS – nothing elaborate or special and certainly shouldn’t be classed as an advanced topic. Not trying to be rude in any way but if someone considers this a complicated, advanced method they really should choose to do something else for a job.

  • Waste

    This is a pure waste of time …

  • http://www.jasonbatten.com NetNerd85

    I’ve been a CSS coder for 8 years. I am also a PHP Programmer.
    Don’t call it Object Oriented and if you need a “framework” for CSS you have MUCH bigger problems…

  • http://autisticcuckoo.net/ AutisticCuckoo

    Amazing! It’s 2009, and there are still people who haven’t grasped the purpose of HTML. They coin trendy new acronyms for methods that try to pervert it into a mediocre page layout language.

    But I suppose it’s in line with the zeitgeist. The surface is all that matters; nobody cares about quality anymore, as long as it looks pretty.

    I’m really getting too old for this business. :(

  • http://www.resveratroluses.com zandrarogers

    there are still people who haven’t grasped the purpose of HTML. They coin trendy new acronyms for methods that try to pervert it into a mediocre page layout language.

  • Jez

    I quite like this, as an OO developer it makes sense to me – but unlike some others I don’t feel that to get any benefits you have to totally switch to OO!

    However, a nice addition (in my opinion but not in a lot of others I know!) would be to add actual inheritance – something like

    .onsalesidebar <= sidebar {
    /* extends .sidebar */
    background-color: #FFA500;
    }

    so I can just use class=”onsalesidebar” instead of class=”sidebar onsalesidebar”

  • http://www.sitepoint.com/ Kevin Yank

    AutisticCuckoo,

    I have the same dream as you: a dream of HTML where every tag, every class, every ID is only there because it contributes to the meaning of the document, and where styles are only applied to highlight that meaning. In my dream, there is ample beauty in universally accessible content potent with undiluted semantic meaning. I fear that in the real world, the depth of meaning we seek to create would go unused and ignored, and we must compromise in order to coexist with those for whom beauty is only skin deep.

    We serve a world where aesthetics matter, and in that world one will always need to apply styles that have no associated semantics, or where the semantics we might find to justify them are irrelevant, or at best tenuous. In this world, our markup must contain elements upon which to hang those styles, and classes of elements that enable us to create subtle variations in style.

    Solutions like OOCSS provide a methodology for adding those style hooks without destroying the semantic meaning of your code or the performance of your site. It would be nice if it weren’t necessary at all, but if one accepts that it is, I believe OOCSS (or something like it) is better than the alternative.

    At least OOCSS doesn’t recommend class names like "width960"!

  • JohnnyWashngo

    Wow – I mean, really, wow.

    Assigning multiple styles to an element is nothing new and has been used for a long time. There is nothing object oriented about that.

    Sounds to me like the author is looking to write a book in the future and needed a catchy web related acronym on which to base it.

    You may find that many people have used this technique in the past without given it a name which implies something that it is not.

  • Anonymous

    I am excited about it. In development, I really se a point with this as long as it concerns only the presentation layer and not the markup. As long as a single minified CSS-file makes it to production I see no point about making it harder than it shuld be to write great CSS.

    However: Adding extra markup is NEVER a good idea.

    A designer might find it useful for the presentation layer. I get that. But it’s possible to get insane results when a designer decides or the markup is altered to ease CSS development.

    In a project at work, 32 sites share one common platform. The HTML and JS are the same, but the CSS are unique to all sites. To make it possible for the 32 crews to add a unique design on top of common markup, we decided to add divitis and span mania on purpose.

    The results: thousands of unnecessary HTML-elements. Large junks of HTML, most of it unuseful. The DOM scripting nearly killed IE7, parsing loads and loads of elements in vain.

    Think of it.

  • vladocar

    I like to suggest new definition for CSS Framework: CSS Framework(Library) is making high level reusable CSS code.

  • joybells

    Again, I’m not sure about the terminology, OOCSS, being a programmer as well. However, I really like the concept that is being conveyed here. It does sound similar though to something we are doing with microformats. On our company websites we define a series of classes that acan be used such as locations, contact-numbers and plant names, etc. Then we also have ‘standard‘ ways of marking up images with captions, and on and on…with the flexibility for applying additional classes to elements, (or should I be saying objects?), if we want the image right or left-aligned.

    From a programmers perspective, I think this talk of OOCSS is confusing. I work extensively with classes in .NET (VB and C#) and Java as well as html and css, but I have never thought of making a connection between a CSS class and a programming/ scripted class. You have left me wondering what is the ‘object’?

  • http://programmersnotes.info KJedi

    I didn’t know this is called OOCSS, I figured something like this myself. Yes, I didn’t develop the methodology, but the principle is clear to me :)
    What I can say – idea is nice, but you should not implement it everywhere. OOP is a good thing, but it doesn’t mean you should write lots of classes for the Hello World application just because it forms the nice architecture. One may argue – OOP in this case makes it easier to support it. Yes, it definitely makes it easier. But not in the “Hello World”. CSS in my projects is not so big to require some framework.

    Resume: Idea is great, it’s definitely worth applying it, but it’s not the “holy grail” of frontend development

  • Niels Matthijs

    First of all, html is about semantics and structure. Working with “added” html is usually the best way to go about it anyway, since in most cases it brings a more solid structure to your html document.

    Where I don’t agree is that you’d need a class like .onlinesale to differentiate a component on a certain page. Indeed it is more portable, but what if you want to reuse it on another page (which is not the online sale page). Coming up with a generic classname is hard enough, but you’ll probably end up with a classname describing the style rather than the semantics.

    Worse is the fact that you’ll have to change your html if they decide to make the sidebar on the online sales page like the normal style again, but leaving the copied ones as is. Rather than simply change the css, you’ll need to elevate the .onlinesale class in the html. This is actually worse.

    One extra remark lies with the styling of the separate components. In an ideal world, they shouldn’t contain any css that places them in relationship to their parent. The parent should contain the styling for the place of its children:

    .parent>* {margin:1em;}

    Sadly, still not possible in ie6.

  • klalex

    The idea is awesome. But I wouldn’t call it object oriented CSS. I see only two principles of object oriented programming is used – encapsulation (properties in classes) and multiple inheritance (means HTML object inherits multiple classes). It’s mainly about style of CSS coding.

  • Hmmmmmmmm…

    This is not OO :-)

    It’s just common sense and allows granular control.

  • Matt

    I like clearly separating appearance from layout within the CSS. I also like using classes to accurately describe the content. I even like adding a modest amount of superfluous tags to facilitate consistent reuse of html code blocks.

    But, I hate that they called it “object-oriented”, it might had been alright if this term hadn’t been coined 30 years ago and is now widely known to mean something very specific. (I’ll blame it on marketing)

  • JR

    Sure, this may not be Object Oriented in the strictest sense, but it does take advantage of Object Oriented concepts, at the very least. The CSS are your class definitions, and the HTML is where the “instances” of those classes are created and used.

    Inheritance is implemented through the use of multiple classes on an HTML element. It’s a little backwards, in that the instance of the class defines the inheritance (sort of… there are are issues with how the cascade works re: order in the actual file), but it’s still a form of inheritance. But JavaScript’s inheritance isn’t conventional inheritance either. (OOCSS even supports multiple inheritance! How crazy is that?)

    I see no problem with calling this concept OOCSS, but I’m thinking of it more as an ideal, rather than a technology. The technology was already there, and doesn’t need any modification for this concept to work.

  • http://www.lopsica.com BerislavLopac

    1. This is not “object oriented”, this is simple ruleset extension.
    2. This is nothing which traditional CSS can’t already do.

    Move along, nothing to see here…

  • Anonymous

    How the $@&” is this OOP? Where is the polymorphism? Doesn’t the C in CSS already imply inheritance?

  • WHAT?

    IT SUCKS.

  • Anonymous

    This is good for large sites, and to create patterns/blocks of html/css that can be reused in many different sites and to do this you have to creat extra HTML.

    When we work with large sites with many templates we created HTML to operate in all templates in different parts of the page, and we have to think that a block may have a title, image, a link, a detail, a icon, but at the end is the client that will put the content and some fields are not required. And all parts of the block have to work independently.

    That sounds like a great idea, is a way to create some rules, exceptions to optimize the rendering HTML or CSS.

  • Anonymous

    Visit the video link and have a listen for yourselves, not too bad if you ignore the OO references. Somehow though, this approach can provide systems and constraints for managing newbie coders, non-savvy cms editors, lazy programmers and quick hacks to ‘fix’ our designs. If that is all we take away from this then we miss out on the on the more important and objective aspect, which I picked up from her presentation as being modularization, code re-use, lighter-weight html and css, etc. which involves lots of careful pre-planning and ongoing teamwork, and quite frankly I think OOCSS stands a chance of failing its true objective in any any context where the developer/ designers don’t pay attention to detail and spend the time to do their job properly.

  • OOP coder

    The worst part about this is the disappointment. I first did OOP in 1986 and I’ve used it intermittently ever since. I love it! When I saw the title of the article, the excitement welled up – “what can this mean”, I thought. Naah. Nothing here is OOP. I think it’s a great way to write CSS, but I often do it this way, so now I’m fed up at the lack of a new idea.

  • http://www.18aproductions.co.uk lisaanne

    I kinda feel this isn’t a “new” form of CSS, more just saying that what we’ve been doing lately should be used more going forward! Really, CSS has always been OO in the loosest sense – applying a class and then determining styles for it. And nesting styles is the “cascading” bit… I know I’m being overly simplistic, but whilst I like the article and agree it’s a good way to go (if you’re doing certain stuff – I take on the point about apps) I feel it’s kinda giving a name to something that’s not all new revolutionary.

    Lx

  • http://www.18aproductions.co.uk lisaanne

    Oh – and I’m really torn on the loading times thing… hmm, overall longer but seemingly quicker… can’t decide!

  • Joe

    Object Oriented Cascading Stylesheets? No. If you are suggesting a new framework, keep it at that, but to use the term “object oriented” is simply wrong.

  • http://www.riaspot.com RIAguy

    As many have pointed out, the term “object oriented” is a misnomer used this way. We web developers have spent a decade now combating the confusion by calling JavaScript “JavaScript” (cause it ain’t Java), and we all know that Ajax doesn’t necessarily mean XML.

    The real issue comes in when you have to explain this to newbies or managers.

    It seems to be fashionable to latch on to and extend popular tech terminology inappropriately. OOCSS doesn’t exist as far as I’m concered.

  • curagea

    A better name would have been “OO practices/ideas in CSS”. To add more blows to a dead horse, OOCSS is a misnomer. When I first heard about it a few months ago, I was expecting some entirely new language as an alternative to CSS, like a spawn of Java/Python/Ruby and CSS. Nope, didn’t happen. Designers/OO programmers will just have to keep dreaming.

  • chobo321321

    It seems like OOP is all the buzz, so the “logical” solution is to try and take an already perfectly fine solutions and “fix” it with OO principles. Sorry for all the quotes :) Honestly, this seems so pointless I’m beyond words. Why would you take something that is so simple, effective, and works well for the masses, and complicate it with yet another set of bizarre syntax and rules?

    Has anyone else stopped to think that enough is enough already. I mean to be a decent web developer, you need to learn at least one server-side programming language, SQL, XML, XHTML, CSS, some sort of graphic editor, search engine optimizations, at least one framework on top of your server-side language, jquery, or whatever the heck you use. You need to learn about hosting, and all the other little shit that changes every six months. For fucks sake leave CSS alone :)

    Honestly someone please tell me what other profession goes through all this in terms of having to stay fresh and updated in your knowledge. Now one can touch a web developer with a 100-foot pole. It just keeps changing so fast and you’re required to know so much, it isn’t possible to specialize.

  • jonathanstark

    I second the point made by the person who said that using OO in the blog post title resulted in disappointment upon learning that there was nothing new to be learned here. This is standard CSS.

  • dvessel

    For you naysayers, this practice may not be entirely new but defining and giving a lucid explanation on its principals and practice is very valuable.

    These days we have large web apps and frameworks spread across many people. Having a common understanding is invaluable. This will less likely resonate for lone devs on smaller sites.

  • arts-multimedia

    Really don’t see the point of this. If someone has difficulties adding classes or selectors to css page, it usually means they do not grasp css or that the author created messy css.
    If the css page is properly written, as we are supposed to do in the first place, it is really very easy to add classes etc …

    It also appears to me that this method just shifts more code to html, which eventually amounts to the same burden.

  • fwolf

    This is not OO – but rather kind of a Pattern applied to CSS. Nothing else.
    If you’re regularely writting programmings utilizing a code framework like RoR, CakePHP oder Groovy on Grails, you already know this style by heart.

    So – nothing new ..

    cu, w0lf.

  • Bobby

    Bad, Bad Bad.

    I received a Sitepoint email describing how to style a sidebar using a class. Surely a sidebar is a big piece of content that would use an id rather than a class. This is just basics…and even if we were to use the class, proper markup would dictate that this main content would end up having an id and a class. More HTML…a bad thing.

  • kneekoo

    This is plain old CSS. Why would anyone mock the concept of Object Oriented Programming? I just can’t figure that out. Has IT become a “sensational story” for tabloids where things get invented right out of thin air for the sake of intriguing the masses? Please stop this madness before it catches fans. Information Technology is a serious business. Don’t trash it.

  • Laolusrael

    Inheritance has always been a part of css. If you want to push the idea of structural css development using the inheritance feature of css that is good. Which I encourage, and you can actually build a good css framework using this methodology. Yes, you can build a framework, and it won’t be more than that considering the fact that different projects have different requirements, but all projects have such this as layout for which you can create a css framework and have your html elements inherit these.
    OOCSS is the wrong name for this right practice (or development pattern). Because there is no OO without all the building blocks in place.
    Then, I also think if you already design the right way you won’t feel any load on your html.
    I can go on and on.
    Its a good point you have made in your article though the wrong name.

  • Ozh

    Seems dumb to me. Larger HTML and smaller CSS? Browsers cache CSS. Make them bigger, no?

  • sitehatchery

    Seems like you could just:

    Where all that follows is related to Layout1 (i.e. layout with wide blue left column).

    And:

    Where all that follows is related to Layout2.

    You could also style the index specifically by using the index ID – which would override any particular layout designations.

    Most websites only have 3 or 4 different page layouts at the most.

    Seems like this would take less time and be easier to code and debug. Because of inheritance, this is more closely related to object oriented coding. The so-called object oriented approach outlined in this article seems more like less-maintainable spaghetti code.

  • sitehatchery

    Nope. What the heck?

    Basically, I have a body tag with an id=”home” and class=”layout1″ or class=”layout2″, depending on the layout.

  • Bryce

    Looks pretty unanimous. NOOCSS!

  • Bubbles

    It’s like trying to write OOPHP in PHP4 all over again! There’s hints of it, but the language just isn’t Object Oriented! CSS4 perhaps? (Insert sarcastic tone)

  • http://www.lopsica.com BerislavLopac

    A former colleague of mine used to have a great term for this kind of activity: saddling a cow. Basically, something which could be done in theory, but is quite complex and utterly useless in practice.

  • http://www.lopsica.com BerislavLopac

    @Sitehatchery: check the bottom of the page: “* Make sure any code samples are escaped.”

  • Nexx

    … Why would you style a body tag for the sidebar? This is standard CSS, not object oriented programming. Disappointing article.


    Object Oriented Web Programing consists of dividing design (the UI), the logic, and the data into their own layers. Most specifications now-a-days practically require this leaving XHTML as the framework for your design (HTML5 will add more meaning to the framework) and CSS/Java manages the design, thus creating the UI. Background logic is often taken care of with systems like PHP/ColdFusion/ASP, which is separated from the core data taken care of by MySQL/SQLite… *sigh* Programming 101.

  • Justen

    I’m not sure I quite get the point yet. You can’t really do “object oriented” with CSS, but you can follow some OO principles: encapsulate what changes, favor composition over inheritance, write to interface rather than implementation, dependency inversion, open to extension, closed to modification – these can all be applied to CSS to some extent or other, but I’m not sure that is what has been accomplished with so-called OOCSS based on this presentation.

    I’ll watch the video soon as I get a chance, maybe that will sell me on the idea better, but for now I’m not biting. It sounds like a way to increase markup *and* complexity while reducing semantics, for the sake of a slight gain in reusability – which is not a great tradeoff. We should be able to accomplish greater reusability without such extreme measures, using microformats and other design patterns and common conventions that don’t increase non-semantic markup.

  • http://www.f6design.com/ jnicol

    I agree with everyone who has already stated “this isn’t OO”.

    Just like CSS frameworks this seems like another attempt to “fancify” CSS, and make it appear more complex than it needs to be.

    Still, I think it’s good for web developers to be exposed to different work methods, and if it takes a fancy acronym to make people pay attention then I guess I can stomach the “OOCSS” label.

  • http://nicholasorr.com SoreGums

    If you do ruby and want css done OO use Compass (as get going quickly point), which is an extension or fomalised way to organise sass which is part of haml. This way you can do all sorts of wonderful things. The result (in a well thought out, lots of variety in layout style) is a single css file that if you had to look after it manually would do your head in.

    Jez up above said this would be good:

    .onsalesidebar <= sidebar {
    /* extends .sidebar */
    background-color: #FFA500;
    }

    In sass it would look like this

    
    =sidebar(!bg = "#f00")
      :background-color= !bg
      :float left
      :width 100px
    .sidebar
      +sidebar
    .onsalesidebar
      +sidebar(#00f)
      h3
        :color #0ff
    

    .sidebar has the base stuff, .onsalesidebar changes the background colour and could even add extra styles if needed (for a h3 in the example).

    for oo in css the closest proper OO i’ve seen is sass :)

  • dimitris.v

    judging from the slides, she has a structured view of css but really isn’t describing something new in this lecture, it looks that she describes the logic behind css which makes it good thing for someone new to css to watch the lecture but not much more than that..

    in a slide she refers to the fact that class order should matter, this would be a life saver if supported, maybe there is a reason it isn’t?

  • hfinger

    Cascading Style Sheets aren’t called that for nothing. So wouldn’t it be equally easy to maintain a soecial page with a custom CSS file that over-rode various stylings of the common CSS file?

  • http://nicholasorr.com SoreGums

    For simple sites that makes sense. Remember one goal of the article is speed.

    If the site has a lot of variety in the way things look that css file could quickly become bloated. Also you’re proposing loading another file, this costs in terms of speed. Then you get into the habit of loading another file, then another, then another, then another. Now you have 10 css files :/

    At the end of the day, what are your end goals :)

  • http://www.digitalidiom.co.uk/web_design_services.php decook

    I’m not sure about “OOCSS” for the majority of us. I like to keep my xHTML & CSS as sparse as possible.

    I think for bigger project / multiple developers it may have some efficiency. But I think, having tried to decipher CCS classes etc for WordPress, Joomla, Drupal themes, etc – it would be more efficient if developers gave CSS # and classes more obvious / common names to help us poor front-end guys. If it’s a sidebar call it #sidebar ! I’ve spent too many hours readings acres of CSS to find a class name that bears no resemblence to it’s ‘object’ and is dependent on other rules. So maybe a better naming convention in OOCSS would help anyway…. unsure !!

  • saski

    Apart from the hilarious name, I think this totally misses the principle of the 3 levels separation (HTML for content/JS for client logic/CSS for style)
    …since we are overloading the element’s class depending on its particular appearance.
    I find it as bad as class=”width960″.

  • joe

    The idea is simple, but not completely new. Those of you complaining about the name, are obviously not old enough to remember the days before OO was only used for programming (am I giving away my age :) In its original usage as a help to map thoughts, the usage here would be correct.

  • http://www.flixon.com jgd12345

    Mattijs Bliek let’s not argue who come up with this because they really have come up with nothing. They have simply coined a term for something we’ve been doing for years. Multiple classes on an element is trivial for a css developer.

  • http://www.wynnefields.com/ Wynnefield

    @sitehatchery: I know it’s very late, and I’m a bit cross-eyed; however, “layout1″ and “layout2″ provide about as much semantic description as “width960″.

    Although I agree (to disagree) regarding the lack of OO in principal, I believe this post can be quite helpful to new CSS coders and/or teams who share style sheets and need sensible, resusable semantic CSS.

  • KansasCoder

    I think some of the commenters are getting hungup on semantics and definitely nered to exit their cubicles more often.

    There are many ways of writing css and this one has merit for being clean, maintainable and has an eye on performance. I see nothing wrong with adopting a methodology or a framework for writing css. All of you lambasting this have done so in other areas of your development so why poo-poo it when it comes to css?

    Nicole has persented an elegant, well thought out and delivered methodolgy based upon her impressive experience and obvious intelligence. Saying “This is nothing new” or “its not really OO” does little to help anyone. It only serves to give your own ego a boost. Why don’t you all post a link to your community contributions in addition to your useless rants? Seriously!

  • biswa

    This is not perfect class base concept, but really great concept.I really enjoy and going to use in my next project.

  • Pacoup

    I made a blog post on my opinions on the subject because it’s too long to integrate in a comment. Read here: http://www.pacoup.com/?p=443

  • Ralph Hardwick

    I didn’t realise there had been a term coined for this. I have been loosely applying these principles for years now without much structure. It has always made sense to me to apply multiple classes to HTML rather than re-use CSS code constantly.

    The name needs to change though, it implies that it is an Object Orientated approach to CSS in the traditional sense of the term in computer science. It isn’t, nor can it be.

    Element Orientated CSS?
    Reusable Selector CSS?
    Element Decoupled CSS?

  • http://www.sky-web.net/ Dr John

    I’m not a cutting edge css user by any stretch of the imagination, but I’ve been occasionally using two or more classes on divs etc for some time. Often the second or third class is a simple option to add bold or a color, but occasionally for more serious changes. Saves re-writing an entire class just to add one or two lines. It’s the same as styling one h2 differently to the rest with a class or id giving some simple change. I don’t usually add an id to the body, as then the code is less reusable.

    OO? No. Useful? Yes.

  • Kelley van Evert

    To all the people above, who have been argueing bitterly whether or not OOCSS is object oriented or not:
    What is the big thing about this OOCSS? I’m a ‘beginning freelance webdesigner’, which means I’ve been coding websites for about a year now, 17 years old. Anyway, I’ve been through various stages in my css coding, sometimes doing it this way, sometimes an other way, and this is just one of them I had some time ago. I like it, but hey that’s the big thing about it? Do people seriously spend whole blogs debating whether this is a good way or not?!
    Weird ;)

  • http://www.csskarma.com timwright

    From my understanding, this is OOCSS:
    <p class="floatright roundedcorners margin10">
    content
    </p>

    Making classes modular so you can reuse them over and over to create elements, rather than doing something like this:

    <p class="floatright-roundedcorners-margin10">
    content
    </p>

    With that being said, I’m not a big fan of this for CSS, it kind of kills half the purpose of semantic css if we use presentation items like this.

  • michai

    Who ever said this was OOP? It’s just object-oriented. Conceptually. Do you take *everything* this literally?

    Spend a few minutes looking into it before whining about what a horrible atrocity the name is, it’s nothing new, etc.

    In other news, Mozilla Firefox isn’t _actually_ a small furry critter who loves in forests.

  • stubbornella

    Great article and introduction to OOCSS! Thanks! Some of you haven’t really looked at the OOCSS code before commenting… the class names you bring up don’t appear anywhere. :)

    @Jez You are absolutely right, it would be much better if browser supported inheritance within the CSS itself. More on that later.

    Calling it OO may irk some of you, but it doesn’t need to be .net, php, or js in order to be OO. In fact, in order to be object-oriented CSS it needs to specifically be CSS and do what CSS was intended to do, which is style web pages. It has many of the components of OO including encapsulation, inheritance, polymorphism, modularity, abstraction. No, it doesn’t have methods. CSS doesn’t need methods.

    The cool thing about the cascade is that you can do things like multiple inheritance, that would be a mess in ordinary programming, but with the cascade are neatly taken care of.

    Keep in mind that this article is an intro, a dip into the subject rather than the full treatment. You might also want to check out this video on the subject or at least look at the code.

  • stubbornella

    Oops, the video embed only works in preview mode. Here is the OOCSS video

    Cheers,
    Nicole

  • McGivrer

    Yes, this CSS implementation is not exactly Object orientation, but this utilization have benefit of the DOM hierarchical structure and the inheritance capability of the Cascade Styles Sheets.

    I Mean, the tag BODY is parent of all DIV tags of your page, so any DIV element “classified” with any CSS class will benefit of any BODY CSS class applied. (Am I clear ? I am not sure, but it’s the idea, and it’s a good one !)

    Thanks to the SitePoint Team to broadcast Good(Best?) practices to avoid monstrous CSS class definition file and incomprehensible.

  • prince_mallow

    WOW! I usually get very defensive when I start reading an article that suggests different CSS stylings. I also at times really hate CSS for it’s multitudes and multitudes of never ending script on a page. I never thought of separating the design aspects from the functionality aspects like that. It is something I will have to try. Enjoyed the article. Truly sorry for the other commenters getting hung up on the word object oriented. It’s really just an inspiration from it’s concept.

  • DAZ

    I think lots of other people have covered the fact that this is not OOP and the name certainly implies it is linked in some way. This causes some potential for confusion.

    The name has managed to generate lots of interest, however, so from a marketing point of view it was an excellent choice.

    This is really just a ‘modular’ approach to CSS, which I would consider best practice anyway.

    The discussion it has generated has made for some really interesting comments, so in that respect this is surely a good thing. I’m not sure it needed a whole framework and code built around it. It is just a methodology and should be discussed in that sense.

    As a methodology, this contains some good ideas. People should definitely be trying to create more reusable CSS. It is a fact that many website contain largely similar items – tabs, vertical nav, sidebars,headers,comments etc. It would make sense to create some classes that could be used to style these elements quickly. I’m sure a lot of people just copy and paste from the last project, but this methodolgy would advocate creating some reuasable ‘modules’ with consistent naming conventions, markup paterns and classnames.

    The arguments that the class names are unsemantic doesn’t hold water. Using unsemantic class names doesn’t lose any semantic meaning, it just doesn’t add any either. If you’re really concerned about it, why not just add some extra class names that ARE semantic? The fact is that if you are creating reusable code, you can’t predict in what context it will be used in future, so the best choice for a class name would be something that describes what it does. I wrote a blog post about this a while ago (http://dazzl.co.uk/blog/don-t-sweat-the-unsemantic-stuff).

  • http://lynnepope.net/ elpie

    I had an indepth look at this some time back and, like others, fail to see how it can be called OO. While I appreciate that a lot of work is going into it, there are some serious shortcomings that make the claim of “maintainable” a bit misleading. “Reusable” – maybe, but then anyone experienced with HTML/CSS, especially in a team environment, is already reusing code anyway.

    Any “framework” that specifies the use of classes with meaningless names such as “unit size2of3 lastUnit” and which, while claiming to be a CSS framework, states that its non-semantic classes should be inserted via a serverside script or JavaScript (huh?) just isn’t worth taking seriously.

    Others have mentioned semantics – what on earth is semantic about classes such as gMail, gCal, yahoo, myYahoo, oldSchool and the like? Anyone wanting semantic output would not touch OOCSS.
    Ideal in a team environment? Maybe, if the team keeps a reference guide handy to explain the jargon.

    With no source order, no semantic document structure, and no apparent consideration for accessibility, OOCMS has a very long way to go before it should be considered worthy of promotion by SitePoint.

  • DAZ

    @elpie

    I agree with you that the structure of OOCSS is very complex (I had a look at the source and couldn’t believe how many files and folders there were!)

    As I said above though, I don’t think the lack of semantics is an issue – a framework by definition cannot know the context in which the class will be used in advance, so cannot give a class name that will be semantic for everybody.

    I have found the best thing to do is just use a class name that describes what it does. So if your class transforms a list of links into tabs, just call the class ‘tabs’. At least then the designers/developers know what that class is there for.

  • Eyveneen

    or just have seperate stylesheets and use the @import rule

  • Anonymous

    I think pretty much everyone hates the misnomer “OO”, but the idea is definitely intriguing. I saw an article a while back about writing CSS this way, so I know it’s not necessarily a new idea, but I’ve never really seen an in-depth discussion of it, just little “hey try it this way” articles.

    Seems like this style is best suited to cases when a designer won’t always be intimately familiar with the CSS, isn’t changing it on a daily basis, will be re-visiting projects after several weeks or months, etc.

    If you’re very focused on a small number of properties and working with the CSS of each on a very frequent basis, then you could probably skip this method of coding.