Stop Repeating Yourself! Adopt Object Oriented CSS (OOCSS) for a Faster Web
By Intern |17 Apr 2012
In a bid to make websites faster and more maintainable, the Fresh Egg web design team has learnt to embrace best practice to help keep source code clean and lightweight. In the third post of The Ultimate Web Design Toolkit series, we’ll explore how to write lighter and more maintainable CSS (Cascading Style Sheets) by introducing the concept of Object Oriented CSS.
Way back in the days of formatting website content using inline HTML such as <font> to style textual content or <table> to layout content, websites were hard to maintain and web designers were limited in design capabilities.
CSS was primarily created by the W3C (World Wide Web Consortium) to strip all content formatting out of the front-end source code and store it in a separate file, a CSS file. CSS enables you to style elements such as layout, colours, and fonts. It improves accessibility, gives developers more flexibility in presentation, and enables multiple pages to share formatting.
How can we make CSS better?
Over the years, the way CSS is written has changed considerably. Historically it was used just to style textual content, and then to style the entire layout of a web page. However, this often meant writing thousands of lines of code, which adversely affected site performance and maintainability.
Then came OOCSS (Object Oriented CSS). OOCSS is a framework created by Nicole Sullivan that encourages developers to write CSS that is lightweight, maintainable and easy to reuse.
There two main principles to keep in mind when attempting to write OOCSS:
1. Separate structure from skin
Every website has repeatable visual elements that could share the same colour, shape or size. You might have elements such as links or panels that contain textual content, which share consistent border styles or background colours but vary in padding and width. For example:
.panel {
background: #333;
border: 2px solid #666;
color: #fff;
padding: 15px;
width: 200px;
}
.link {
background: #333;
border: 2px solid #666;
color: #fff;
padding: 5px 10px;
width: 100px;
}
As you can see, there are duplicated styles, within the code. Through the use of OOCSS, the code can be reworked to create a global skin class alongside the shared properties. This also has the added benefit of creating reusable elements. For example:
. panel {
padding: 15px;
width: 200px;
}
. link {
padding: 5px 10px;
width: 100px;
}
.skin {
background: #333;
border: 2px solid #666;
color: #fff;
}
Easy ah? By doing it this way, you make CSS reusable, maintainable and lightweight.
This is how the HTML should look: