An Overview of OOCSS, BEM, SMACSS (CSS Methodologies/Practices) with References

Writing CSS is really simple, we’ve been doing that since many years. But the problem is, in larger projects where the CSS code grows over thousands of lines, whether you’re alone or it is a team maintaining and building on the code, it gets really unwieldy (spaghetti code). Code gets hard to maintain, harder to debug, unoptimized leading to poor performance and highly inefficient. New team members start adding more code (classes, IDs, etc.) and start using them leading to a lot of redundant and unoptimized code here and there. Basically it gets hard, really hard. You end up into too many issues.

Smart people across the world have tried to solve these pain points by working on various solutions like pre-processors, standards, methodologies, etc. In this article we’ll just take a look at some of the famous methodologies employed by a lot of professional front end engineers. Although all of them boil down to a couple of similarities, we’ll just go through what they emphasise on and how they can improve not only the code maintainability but also increase efficiency in terms of building up and performance.

The methodologies we’re doing to discuss are OOCSS, BEM and SMACSS. The idea behind writing this article is to first discuss these methods and then get a radical new (relatively) approach that a lot of developers have been taking of writing CSS to further solve issues that these standards couldn’t address well. The new approach is writing CSS in JavaScript but we’ll discuss that later, maybe another post.

OOCSS

There are a couple of articles that covers the concept of OOCSS (Object Oriented CSS). About OOCSS, you’ll read a lot of stuff like:

  • The OOCSS methodology encourages reusable CSS which is faster (efficient), scalable (building onto) and maintainable. Reusability will lead to less repetition and clearer code leading to very low complexity that directly impacts performance and maintainability.
  • OOCSS concept sort of comes from traditional languages like PHP or Java. Right, you might not be able to make any sense of that statement, so in simple terms, objects in OOCSS refers to components (imagine a simple button that can be re-used all over in footer, header, sidebar, main content area, etc.) that can be represented by an independant HTML snippet as well as in CSS by a set of selectors with one main selector representing the component. So imagine breaking down a web app (or website) into multiple components, each of them would be an object. It can be a button, a small widget in your sidebar (showing “Recent Blog Posts” for instance), navigation bar in the header, etc.
  • With OOCSS you end up building components that are re-usable and independant of their location, i.e., parent container. They can be present in the sidebar or the footer or the main content section, yet they’ll look the same. But they’d definitely be customizable.
  • Re-using means better performance as you just repeat the structure (HTML) for reuse and it works without any extra CSS, saving hundreds/thousands of lines in a large project.

In a nutshell, there are two main principles of OOCSS:

  • Separate Structure and Skin.
  • Separate Container and Content.

Let’s first talk about what separation of structure and skin mean. Structure is the layout aspects (width, height, float, margin, position, overflow, etc.) whereas Skin is the styling aspect or the visual features (background, border, etc.). So for a particular object, create two different classes targetting structure and skin and then use both of them to eventually style the object (component/module). Let’s see a super simplified example:

/* Without OOCSS Methodology */

.button {
  width: 100px;
  border: 1px solid black;
}

.widget {
  width: 200px;
  overflow: hidden;
  border: 1px solid black;
}

/* After applying OOCSS strategy */

.skin {
  border: 1px solid black;
}

.button {
  width: 100px;
}

.widget {
  width: 200px;
  overflow: hidden;
}

Although the example doesn’t demonstrate real-world problems, but hopefully you can relate this to larger projects you’ve worked on and imagine how it could lead to re-usability. Eventually you’d use .skin with both .widget and .button HTML objects. You might be wondering that this is common sense (so do I), but preparing a standard that says “keep in mind to separate skin and structure while writing stylesheets” can make sure you just do that sort of separation which according to OOCSS helps write larger CSS projects.

The other principle is to separate the container and content. Imagine a feed section in the sidebar. Now if you move this to the content section or the footer, it’s appearance should not change. So basically, the container (parent) should not affect the appearance of a particular object, i.e., the object should not inherit styles. Now this principle is one which requires greater attention and might be something new to you if you’ve been writing CSS for quite some time without following any methodology or haven’t thought of working on fixing issues that are encountered while moving components here and there or when a third-party plugin is integrated that affects the styles of almost all other objects with similar class names (or tag based selectors).

So in practise, this is done by not specifying or rarely using location-dependant styles (as suggested by the wiki). So to give you an example, if you’ve a .sidebar with a .widget (our main object in this example) which contains an h3, do not style style the h3 like this:

.sidebar h3 {
  /* Bad */
}

.widget h3 {
  /* Bad */
}

.widget_heading {
  /* Good */
}

Why are the bad ones bad ? Because it’ll affect all the h3 in the entire hierarchy. Or when moved to a different parent altogether, some other style (imagine .parent h3, which might even come from a third party plugin) might affect the h3. By specifying a specific class, we get rid of those issues along with nesting (.parent .child) and property cancellation/overriding down the hierarchy due to cascading (what C stands for in CSS, ugh!). This way we also achieve a flat hierarchy with a low specificity (which is good).

Now you might be thinking, this approach will lead to so many classes. An object with four children means almost five classes (even more depending upon the hierarchy). Well yes, that’s true. “Classitis” will probably be inevitable, but the advantages of it in terms of maintainability will outweigh the con which is … what?! Too many classes! Infact as efficient frontend engineers (or web developers), we’ll have to strive to find a balance. Infact it can be mitigated to some extent with multiple selectors at a shot. Let’s see an example. Here’s a piece of HTML:

<span class="label label-primary">Primary Label</label>

and this is the CSS:

.label {
  display: inline;
  color: white;
}
.label-primary {
  background-color: blue;
}

So to overcome excessive usage of classes, your new HTML would look like this:

<span class="label-primary">Primary Label</span>

and the new CSS:

.label, .label-primary {
  display: inline;
  color: white;
}
.label-primary {
  background-color: blue;
}

Infact, using a pre-processor like SASS, you can make re-write this as:

.label {
  display: inline;
  color: white;
}
.label-primary {
  @extend .label;
  background-color: blue;
}

But extending (or inheriting) in a pre-processor can have its own disadvantages and is super error-prone. This article gets into the gory details of the complications.

Now if you notice/remember, bootstrap seems to be quite object oriented (atleast follows the second principle quite a bit).

All said, people do have problem with OOCSS due to the verbosity of HTML (too many classes). They also consider this to be non-semantic. But I think if it solves the problem of maintainability (which it does if implemented wisely), then it might be worth a shot. Infact if you code CSS wisely, then you’ll anyway end up writing something along the lines of OOCSS’s methodology is what I believe.

BEM

BEM (Block, Element, Modifier) is a methodology that targets class naming conventions for various HTML elements by breaking the entire webpage into multiple blocks and elements (components). This article is a darn good introduction to BEM and pretty much covers the fundamentals. Do read the comments section too which is really useful as it solves a lot of common queries. Let’s talk a bit about the fundamentals:

  • Block – Think of it as a component that can be reused in a webpage. Simplest example is a button (.btn { }).
  • Element – The button can have multiple elements inside it. Imagine a button with two children, .btn__text { } containing the “Buy Now” text and .btn__action { } representing the shopping cart (or some other) icon.
  • Modifier – These are additional classes that modifies the visual appearance (skin) of a block or element. For example: .btn--green { } or .btn__text--big { }.

Note the naming conventions of the classes. Elements are namespaced using the Block names and separated by __ (double underscores) whereas the Modifiers are separated by -- (double hyphens). Why double hyphens or underscores ? As your classes can be delimited by a single hyphen or underscore. Let’s see some code for some clarity (from the same article).

<!-- HTML -->
<a class="btn btn--big btn--orange" href="http://css-tricks.com">
  <span class="btn__price">$9.99</span>
  <span class="btn__text">Subscribe</span>
</a>
/* CSS */
/* Block component */
.btn {}

/* Element that depends upon the block */ 
.btn__price {}

/* Modifier that changes the style of the block */
.btn--orange {} 
.btn--big {}

So the core idea of this methodology is to componentize your entire webpage structure by using lots of classes and then also separating the look and feel of components into modifiers. If you notice these two principles are similar to that of OOCSS.

Although surely just like any other methodology, there are people with a couple of valid concerns or concerns that are valid to some extent that go against BEM mostly because of its syntax than as a concept. Let’s see a structure in terms of CSS selectors inspecting such point of views.

.search_form
.search_form__searchbar
.search_form__button

A valid concern is, we’d be better off with:

.search_form
.search_form input[type="search"]
.search_form input[type="button"]

Now that is against BEM rules and might be fine for a small project handled by a solo developer. But imagine when multiple developers are working. It’s a matter of time when some requirement will lead the developer to add another block inside the form that will contain similar input elements. Then all of them will get affected by the same styles which might be quite unwanted. This is also why tag/element based selectors shouldn’t be used directly. Now if you want to get around the BEM syntax yet take advantage of the concept then check out Rstacruz’s RSCSS which is quite similar. Personally I find it quite right and would probably want to use it over BEM.

SMACSS

SMACSS (pronounced “smacks”) is another style guide which is very much similar to BEM. The differences that exist are in naming conventions and a couple of extra rules that they suggest to follow. You may read up the entire book they have on their website (should take an hour) or just know that it’s similar to BEM taking a different approach by categorizing CSS rules:

  • Base Rules
  • Layout Rules
  • Module Rules
  • State Rules
  • Theme Rules

Base rules are used to set the “base” styles of elements via element selectors without using IDs or Classes. Pseudo classes can be used. Example:

body {
  background: #eee;
}

a {
  background: #4183C4;
}
a:hover {
  background: #2B6196;
}

Layout rules are used to style layouts which are major components containing minor components (or modules). You can use ID selectors for these or classes also where the convention is to prefix the classname with l- or layout-.

#header, #footer {
  width: 100%;
}

.l-content {
  width: 80%;
}
.l-sidebar {
  float: right;
  width: 20%;
}

Module rules are used to style modules which are basically components. If you recognize components from BEM or objects from OOCSS, modules are the same thing here. Modules should be able to easily move around and still look the same, i.e., no dependancy on its parent for visual appearance. This is achieved by using lots of classes for almost all the elements in a particular component. Let’s take an example (notice the class naming convention for children):

<a class="msg" href="/messages">
    <span class="msg-text">Messages</span> 
    <span class="msg-count">14</span>
</a>

State rules are something not mentioned in other formats, but they definitely make sense. You basically use classes like .is-collapsed or .is-active to appropriately affect the visual appearance of a module or layouts. In many cases they’d be overriding styles from their base module or layout. If the state is for for a particular module then the name should include the module name too, .is-msg-hidden for instance.

Theme rules is not a core type like the others. Imagine them to affect the skin (look and feel) of the webpage by overriding styles and affecting any of the primary styles from a different stylesheet (better maintainability). If you know general theming, then you know what this means. Many of you would have written theme stylesheets in a CMS like WordPress or build different themes for your own blogs/sites.

All said, the core idea again is to build components that can be reused by using lots of classes, if you notice. Avoiding IDs and element/tag selectors means lesser expectation of a specific HTML structure. Using .module span is still allowed if you’re sure that all the span in the .module will be styled the same way. Also using element selectors within one level of a class selector is also fine, i.e., using child selectors (.module > a) or even descendent selectors (.module a) making sure that anchors only exist in the first level of .module.

In Review

So as you’d have already noticed, all of them in some way or the other ask you to break your structure into components and separate the look and feel CSS from the structural CSS so that the classes associated with look and feel can be re-used across (sidebar and footer might share a lot of styles in terms of colors and backgrounds). So which methodology to use ? Well there’s no perfect answer to that but most people just prefer the BEM syntax of classes. You might think that BEM looks ugly but the advantages outweights the not-so-cool-looking double underscores and hyphens. Other than that namespacing is fine and makes a lot of sense when we as developers or other devs of our team come back to read code and maintain it. CSSWizardry explains it even better. It definitely is helpful on a medium to large scale project whether you’re a solo developer or in a team. BEM with the idea of base, style and theme rules from SMASCC would be quite natural/obvious.

After going through so much of information, I’d vote for BEM or RSCSS. Although whichever methodology you follow make sure you stick to it and the other engineers in your team do the same. The standards should be fairly enforced across the team and code reviews should be meticulous. With the standards you’ll end up clubbing your components code together (as well as common/base styles) which means devs will know where to look for in order to make a change required by the project/product manager. This will sort of ensure re-usability rather than them creating new styles here and there which gets useless as unused over time. I might be repeating myself now but these practises help create components with unique class names that prevents clashing with styles from other components or even third party libraries that is really useful (apart from the reusability aspect).

Further Reading

You should have a good overview of the various practises by now but here are a couple of other links you might want to read and explore more:

Advertisement

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

Leave a Reply

Your email address will not be published. Required fields are marked *

*