There’s a common phrase that get’s tossed around all the time in the web development world, object-oriented programming. Usually when brought up, it’s in context of some back-end language like PHP, but what about for us front-end guys? Can we take this concept and apply it to the ever-changing landscape of CSS? The answer is yes, we can! And doing so will turn your CSS markup into a lean, mean and clean high performance styling machine. Let’s dive into object-oriented CSS!
Why should I care about Object-Oriented CSS?
Great, just what I needed, another new best practice concept to learn. Everyday it seems like there’s a new “best practice” idea you should be implementing in your project. So why should you use OOCSS and is it going to stick around?
There’s a couple of good reasons why as a developer you will want to write your CSS in an object-oriented way. Another common phrase thrown around in the web development world is “reusable” and the first reason why you should write OOCSS. In addition, making your CSS reusable will inevitably make your stylesheets become much smaller and easier to manage. OOCSS should make changing the design of your site easier.
You’ll also gain peace of mind when writing your styles this way. How so you ask? It will be mush easier to change parts of your site without breaking it. Keeping your CSS object-oriented enables you to change your site consistently.
Object-Oriented Programming, an easy concept to grasp
Object-oriented programming isn’t a new idea, it’s been put into practive since the late 1950s starting at MIT in the environment of the artificial intelligence group. According to Wikipedia,
Object-oriented programming (OOP) is a programming paradigm that represents concepts as “objects” that have data fields (attributes that describe the object) and associated procedures known as methods. Objects, which are instances of classes, are used to interact with one another to design applications and computer programs.
In layman’s terms, OOP is the practice of making your code reusable, efficient and fast. So how do we apply that idea to CSS?
Make Way for OOCSS!
Object-Oriented Cascading Stylesheets or OOCSS for short introduces object-oriented programming to the wonderful world of CSS. OOCSS, at its core, is simply writing less and cleaner CSS. It’s not a different language: still the same old CSS we all know and love. It’s just a paradigm shift. Really, object-oriented CSS is a few simple patterns and best practices.
I first learned of OOCSS from Nicole Sullivan (worked on the high performance team at Yahoo!) when I watched her presentation, Object Oriented CSS: for high performance we applications and sites. If you have about an hour, I’d highly suggest watching her presentation because she does a great job in explaining OOCSS and how to implement it. To understand OOCSS, you need to understand it’s two main principles: Separation of Structure from Skin, Separation of Containers and Content.
OOCSS: Separation of Structure from Skin
I never went to college for web development or programming so I’ve never liked those long, big-worded explanations about what certain terms or concepts meant. So I’m going to try my best to break it down for the layman’s like me out there. Separation of structure from skin basically means you put the layout classes or the classes you create to position regions on your webpage like grids from the visual features of your site or your site’s
skin. Think of the structure like the foundation and wood framing of a home and the skin as the paint, wallpaper and other ascents. I’m more of a hands-on learned so here’s an example:
CSS before Implementing OOCSS
Here’s a block of CSS before any OOCSS concepts are applied to it.
Take a look at the CSS above. It’s valid CSS, however it could be optimized and made reusable using the OOCSS concept. Currently it uses non-reusable ID selectors to define styles. If you take a closer look, you’ll also notice they have a number of styles in common. Those common styles may be required to be consistent with the product or company the website represents.
CSS after Implementing OOCSS
With a little bit of planning and forethought, we can abstract the common styles so the CSS would end up looking something like this:
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 possibility for further reuse.
Something to keep in mind…
When coding OOCSS, it’s important to make all styles you create as generic and adaptive as possible. A general rule of thumb is to try and never use defined widths and heights. The content should be able adapt accordingly while keeping the same look. This is true for most all styles in OOCSS.
For instance, let’s say you have a widget container inside a right column container. The right column container’s width could depend on a number of factors from the user’s screen size to the page type. You’ll need the widget container’s width to adjust accordingly so it fills all the horizontal space in the right column. In the example above, we’re defining the widget container’s width which wouldn’t allow it to adjust accordingly. Instead, if we left out the width definition in the widget class, it could dynamically fill all the horizontal space in the right column container. Make sense?
OOCSS: Separation of Containers and Content
The second principle of OOCSS is the separation of containers and content. We should rarely use location dependent styles, because those styles then become locked into specific selectors. The “skin” of an object should look the same no matter where it’s located. Take a look at the example below:
The style above locks all h3’s that appear in the sidebar container to a certain look. Also, this approach doesn’t allow the use of this style in other sections of the site like the footer. But what if we want to apply those exact same styles to h3’s that appear in the site’s footer with the exception of a different font size and a modified text shadow. To accomplish that there will be some duplication of code, see below.
I’m sure the above looks familiar. I’ve written css like this and I’m sure you have to. The code above now unnecessarily duplicates styles, BAD! But now with OOCSS, more forethought is required to figure out what is common among different elements. Then you must separate those common features into modules or objects that can be reused anywhere on the site. Doing this avoids the problem of needing to overwrite styles over an over again to achieve the desired result and avoids creating specificity issues.
Here’s a real world example. On the project I’m currently working on, we have default list stylings, another set of styles for our global navigation list and yet another for secondary navigational lists. Later on, we may want to add even more random lists that could appear in a sidebar or footer. The old way of doing CSS is to write what your default styles will be and then override those styles for the various different lists. This can get overwhelming, hard to manage, and cause code duplication.
To combat that, we spent a little bit more time upfront thinking about the common elements that will appear on the site and then abstracted those commonalities out into reusable modules. We didn’t attach our modularized classes to specific elements so it will allow us to add the box styles to any container.
The Bottom Line on Object-Oriented Cascading Stylesheets
I’m famous for saying,
just give me the bottom line. Well here it is for object-oriented CSS, some simple guidelines to follow when implementing the OOCSS concept in your next project:
Object-Oriented CSS Guidelines to Follow
- 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 Lint to check your CSS (and know that it has options and method to its madness)
- Use CSS grids
For the Overachievers
Being in the IT industry, I know there’s many of you that eat this stuff up like it was candy. For the dedicated out there, here’s some additional resources you can use to learn more about object-oriented CSS. I would also highly suggest following Nicole Sullivan if you want to continue learning about OOCSS. In addition to posting articles regularly on object-orientated CSS, Nicole has done a number of presentations with accompanying slideshows. Here’s some that I would suggest checkout out:
A Little Extra on Object-Orientated CSS
Nicole Sullivan gave a talk at An Event Apart in Boston, MA on Object-Oriented CSS. She shared ways to optimize CSS code and why performance matters for websites. Here’s some of the important points worth mentioning:
- Yahoo! 5-9% drop in full page traffic from an added 400ms
- Google lost 20% of searches from an added 500ms
- Shopzilla improved Website performance by 3.5 seconds and conversion rate went up 7-12% and page views went up 25%
- Bing and Google added added 200ms to a page it took people 500ms to make a first click. People get out of their flow when performance degrades
- Over time, as you slow down user experience, people’s interactions get worse and worse. Even when people’s performance gets improved, if you lost them before, they may not come back. Build performance into your process.
- Active users are the ones most impacted by performance. Time to click is two times worse than the delay was. Your users care about performance.
- The biggest thing you can do to improve performance is reduce file size and number of http requests. CSS is a factor in both of these. We have to do CSS right.
Issues with CSS
- CSS code is too fragile -even the cleanest code can get ruined by the first non-expert to work on it. CSS requires expert ability to just get started.
- Code re-use is almost non-existent. Most people start over when writing CSS.
- Because of these issues, file size just keeps getting.
- Browsers all have default styles. All these internal style sheets are different. A CSS reset sheet can make things equal across browsers.
- Browsers ignore code they don’t understand. Invalid property values are skipped.
- The order of classes does not guarantee which one will be applied first.
- The last property value pair in a CSS declaration is the one that applies.
- The order of style sheets also matters. The last style sheet wins.
- CSS inheritance: properties are inherited by child elements. For example, paragraphs inherit the font-size of the body.
- IDs win over classes. Inline styles win over external style sheets. !important wins even over inline styles.
- Avoid ID, inline and !important when styling elements. This allows cascade order to determine the winner.
- You can use the cascade ordering of styles to save code and improve performance.
- Avoid applying styles in a “.message.error” manner. This causes issues in some browsers.
How to Optimize CSS
To optimize CSS: reduce duplication and improve predictability (don’t change expectations based on where the component is).
- Analyze how much duplication there is.
- Find simple solutions. Problems may seem complicated but that does not mean they necessarily are. Determine what you can know about each object and determine what you can’t know.
- Simplify specificity: use hacks very sparingly and in way that does not impact specificity.
- Avoid styling IDs: they impact specificity and can’t be re-used
- Avoid styling elements: style classes instead
- Avoid !important :except on leaf nodes
- Give all rules the same strength: use cascade order to overwrite previous rules.
- Reuse elements: this makes them performance “freebies”
I know there’s probably a lot of you out there that fear the OOCSS ideology because it appears to go against a lot of the so-called “best practices“. Never fear! Once you understand the benefits of using OOCSS, I have no doubt that you will convert.
Even though there are new frameworks, best practices, concepts and technology coming out daily, I think overall object-oriented CSS will stick around in the future of CSS development. I strongly believe it’s a concept that all developers from back-end to front-end should incorporate into their projects.