The Fresh Egg blog
Latest digital marketing news
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.
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:
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:
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:
Easy ah? By doing it this way, you make CSS reusable, maintainable and lightweight.
This is how the HTML should look:
Making your CSS location dependent is not good practice. The styles become too specific to a location, which makes it harder to maintain, and encourages you to constantly overwrite the styles. For example:
By styling the <p> tags specific to a location you are causing unnecessary duplication. Instead, create and apply a class that describes the <p> in question, like <p>. The benefits of doing this are:
Created by Nicole Sullivan, the media object is a reusable module that will save writing lots of code because you don’t repeat yourself. Here’s an example:
It’s simple, can be nested, and is reusable. Here’s how it will look: