OOCSS - The Future of Writing CSS
As web projects grow, managing CSS can quickly become challenging if you don't put any forethought into how the code should be structured. Fortunately, some smart developers have come up with several methodologies to help programmers write CSS that is succinct and easy to maintain. Object oriented CSS, or OOCSS, is one such approach that can be applied on its own or combined with other methodologies like BEM to impose order on naturally disordered CSS.
What is OOCSS?
Object oriented CSS was proposed by web developer Nicole Sullivan in 2008. Her goal was to make dynamic CSS more manageable by applying the principles of object oriented design popularized by programming languages such as Java and Ruby. Using the OOCSS framework results in CSS that is reusable, scalable and easier to manage.
OOCSS draws upon many concepts in object oriented programming including the single responsibility principle and separation of concerns. The goal is to produce components that are flexible, modular and interchangeable.
What is the "object" in OOCSS?
OOCSS is not its own language. Anyone who understands CSS can easily grasp the OOCSS approach. In CSS, the "object" can be any repeating visual pattern that can be specified in snippets of code. Page elements and even groups of elements are given object classes, which are treated as single entities in style sheets. Unlike SMACSS, which gives programmers less freedom for categorizing objects, OOCSS is relatively easy to master.
The first rule of OOCSS: Separation of structure and skin
OOCSS has two major underlying principles. The first is establishing a clear division between structure and skin.
The structure of an application refers to things that are "invisible" to the user such as instructions for element size and positioning. These properties include:
- Height
- Width
- Margins
- Padding
- Overflow
An application's skin refers to the visual properties of elements such as:
- Colors
- Fonts
- Shadows
- Gradients
In other words, the structure consists of the instructions for how things are laid out, and the skin defines what the layout looks like. OOCSS defines them separately.
For example, the following code represents how two buttons of the same size but in different colors would typically look like in CSS:
.button {
width: 150px;
height: 50px;
background: #FFF;
border-radius: 5px;
}
.button-2 {
width: 150px;
height: 50px;
background: #000;
border-radius: 5px;
}
The above snippet contains a lot of repeated code to define things such as width
, height
and border-radius
. Such repetition can clutter a website's style sheet, which makes editing increasingly difficult. Using OOCSS, we can pick out the patterns that are common to all skins inheriting the same properties. Doing so condenses the above CSS to the following:
.button {
background: #FFF;
}
.button-2 {
background: #000;
}
.skin {
width: 150px;
height: 50px;
border-radius: 5px;
}
Although it doesn't look like much of a difference in this small example, the benefits compound as projects grow larger. By defining all elements separately as classes, we have created a reusable skin for styling the structure. Now, you can apply the class to the element with the following HTML:
<a class="button skin" href="#">Home</a>
<a class="button-2 skin" href="#">Blog</a>
The second rule of OOCSS: Separation of container and content
Separating containers from content makes for a more consistent and predictable user experience. In this context, content refers to elements such as images, paragraphs and div tags that are nestled within other elements, which serve as containers. Most containers can be represented by a structure class.
For example, you can use the class combination btn-small btn-red
to ensure that you see a small, red button regardless of the container it appears in so long as the structure class btn-medium
and skin class btn-red
are written independent of a container.
As a general rule, styles should never be scoped to particular containers. Otherwise, you'll be unable to reuse them without applying overrides. For example, below is the standard way of setting up the elements that make up a sidebar:
#sidebar {
padding: 2px;
left: 0;
margin: 3px;
position: absolute;
width: 140px;
}
#sidebar .list {
margin: 3px;
}
#sidebar .list .list-header {
font-size: 16px;
color: red;
}
#sidebar .list .list-body {
font-size: 12px;
color: #FFF;
background-color: red;
}
Now, here are the same coding instructions with the content and containers separated:
.sidebar {
padding: 2px;
left: 0;
margin: 3px;
position: absolute;
width: 140px;
}
.list {
margin: 3px;
}
.list-header {
font-size: 16px;
color: red
}
.list-body {
font-size: 12px;
color: #FFF;
background-color: red;
}
Avoiding child selectors is a good strategy for maintaining separation between content and containers. Be sure to bestow unique classes to unique elements.
The benefits of object oriented CSS
Object oriented CSS is a popular approach to coding for many reasons. Below are 6 benefits of using object oriented CSS.
1. Speed
Cutting down on repetition helps applications run faster. CSS files have a habit of expanding exponentially as websites grow in complexity, thus increasing web page size. Specificity is important, but often CSS files contain way more information than is necessary. When using OOCSS, just follow the DRY rule: Don't repeat yourself. Consequently, you'll have CSS files that are smaller and quicker to download.
2. Scalability
OOCSS allows you to freely mix and re-apply classes on different elements without much regard for their context. Therefore, instead of piling on tons more CSS each time a project is passed from one developer to another, newcomers to a project can reuse what their predecessors have already abstracted out.
3. Efficiency
Having fewer blocks of code makes CSS easier to scan, which makes editing and updating less of a hassle. By using previously specified styles for different elements, not only will your code work faster; you'll work faster too.
4. Maintainability
Adding or rearranging HTML markups no longer requires you to rethink your entire CSS flow. This is especially helpful for larger ongoing projects.
5. Readability
When other programmers see your CSS, they should be able to quickly understand its structure.
6. Relatability to other concepts
Understanding the object oriented methodology makes it easier to learn programming languages like Ruby. Conversely, anyone who already understands Ruby can quickly pick up OOCSS.
The disadvantages of using OOCSS
Although there are many advantages of using OOCSS, there are also a few drawbacks. These include the following.
1. Increases the number of classes added to an element
As there is much more separation in the way classes are created, you may need to add multiple classes to an element to account for all of the styling elements. This can cause some confusion to those who aren't familiar with OOCSS and can clutter your markup.
2. May be overkill for small projects
OOCSS certainly isn't required for all use cases. For smaller projects you may opt to not use it at all and that's completely fine. As mentioned above, a few of the main benefits are: scalability, readability, and maintainability. As projects grow, these aspects become harder to manage which makes OOCSS a great tool, however, these aren't as pressing for smaller projects.
3. Requires a learning curve
It may be that other web developers or designers need to make adjustments to your code. However, if you're using OOCSS and your co-workers aren't familiar with it, this will require the need for them to learn how to use it before proceeding, which takes time.
OOCSS vs SMACSS vs BEM
OOCSS is just one of several ways to structure CSS. The other two major methodologies are BEM, or Block Element Modifier, and SMACSS, or Scalable and Modular Architecture for CSS. Each approach is equally effective at making CSS more efficient, so what you should use for your personal projects is up to your preference. As can be seen below, according to Google Trends, BEM is still amongst the most popular of CSS methodologies.
Professional coders should be familiar with all three methods and know how to combine them.
Using OOCSS with Sass
Sass, which is an appropriate acronym for syntactically awesome style sheets, is a scripting language that interprets into CSS. Sass makes life easier for frontend developers by allowing coding with variables, functions, mixins, advanced linting tools, nesting and compilation methods. The object oriented approach can also be applied to Sass to make code even easier to manage.
For example, because establishing objects in OOCSS involves defining classes, it creates some semantic issues. Any change to your styles requires HTML editing, and you have no safe way of accessing some DOM elements.
The Sass @extend
directive gives you access to placeholder selectors, which allows you to create semantic CSS classes. By using placeholders as objects, you can define classes by merging them through @extend
. When you apply properties of one class onto another with the Sass @extend
directive, the properties don't get duplicated; the two classes are simply combined with a comma selector. This feature enables you to update CSS properties in one location. If you're writing really long style sheets, this simple trick can shave hours off of your workload.
For example, the snippet of code below is perfectly logical, but it is not semantic:
a.twitter {
min-width: 100px;
padding: 1em;
border-radius: 1em;
background: #55acee
color: #fff;
}
span.facebook {
min-width: 100px;
padding: 1em;
border-radius: 1em;
background: #3b5998;
color: #fff;
}
To clean up this code, you could use @extend
to mix base objects. As a result, you'll get more manageable CSS that doesn't require you to constantly change your HTML:
%button {
min-width: 100px;
padding: 1em;
border-radius: 1em;
}
%twitter-background {
color: #fff;
background: #55acee;
}
%facebook-background {
color: #fff;
background: #3b5998;
}
.btn {
&--twitter {
@extend %button;
@extend %twitter-background;
}
&--facebook {
@extend %button;
@extend %facebook-background;
}
}
Now, you have efficient, semantic code ready for reuse in your HTML:
<a href="#" class="btn--twitter">Twitter</a>
<a href="#" class="btn--facebook">Facebook</a>
Whichever approach or approaches you use when writing CSS, anything beats managing messy code. Putting a little planning into how your CSS is structured will give you more time and energy to focus on creative endeavors instead of shifting through cluttered CSS.
Tips for writing object oriented CSS
The practice of OOCSS is still evolving, so there are no definitive development guidelines for programmers to follow. Nonetheless, here are a few suggestions for cleaning up your CSS using object oriented principles:
- When you code, you should always think about the next programmer who might build upon your project. For example, you can write an application that performs perfectly to handle tasks in your workplace, but if the code is inaccessible to the next person who takes your job, your perfect program can become more of a liability than a convenience.
- Skin separation can make simpler styles like borders or backgrounds even simpler. For instance, if you have several objects that you want to have a purple border, you should create a separate class for the border and the add it to your objects. This can significantly reduce your amount of CSS code.
- Avoid adding styles based on location. For example, instead of targeting all of the links inside a div to highlight, create a highlighter class that can be reused.
- While OOCSS cuts down on deep nested selectors, you obviously will end up with a lot of classes and more HTML. Using Sass can help cut down on bloat.
- Chaining classes together provides additional features. Any element can have dozens of classes attached to it. This flexibility gives developers the power to establish a library of reusable styles for an infinite number of page elements.
- Standards for naming classes are still being debated, but everyone agrees that class names should be short yet descriptive. As always, think about the next person who will be looking at your code.
- Avoid multilevel descendant class specificity; that's the whole point of using an object oriented approach.
- When extending elements, use targeted classes instead of parent classes.
- Creating a table of contents can help you organize your style sheet into sections.
- If you don't have a large number of repeating visual patterns in your code, applying OOCSS may be impractical. Nonetheless, it may be beneficial to get into the practice of separating structure from style and content from context when writing CSS.
The object oriented option
Keep in mind that OOCSS is a dynamic, or bottom-up, approach to coding rather than a procedural, or top-down, approach. If you're collaborating on a project with a big team of programmers, agreeing on a CSS methodology upfront may be challenging, yet introducing standards early on certainly pays off for everyone in the long run. Whether you settle on OOCSS or some other methodology, you should get into the habit of condensing and organizing your CSS.