Everyone who tried to convince me to use modular CSS was wrong, including me.

Eugene C
2 min readMay 21, 2015

Why do you need to think about modularity at all? You don’t until you have a rapidly changing, large project with some similarly designed elements placed on multiple pages. At this point, you think, “It would be nice to reuse the element CSS code.”

tl;dr

Demo and code.

Modularity to the rescue!

Independence is at the very core of modular CSS. There are best practices and methodologies structured around this idea.
BEM, OOCSS, SMACSS and many other approaches were born. Unique class names are a critical requirement for making independent modules. A module name is used as a prefix for all class names of module elements; it’s a type of scope.

Typical landing page

On a typical landing page, the page header has a logo, headline, authorization, button, and quote modules.

Button and quote modules might look like this:

<div class="button">
<span class="button-text">Get Grammarly</span>
<span class="button-subtext">It's free</span>
</div>
<div class="header-quote">
<h2 class="header-quote-text">
— Grammarly quickly and easily makes your writing better.
</h2>
<div class="header-quote-logo header-quote-logo__forbes"></div>
</div>

Class names in CSS:

.button
.button-text
.button-subtext
.header-quote
.header-quote-text
.header-quote-logo
.header-quote-logo__forbes

This approach is not ideal. Class name conflicts are still possible. Long name usage is not easy.

Modern tools will change this.

The Future

CSS transformation. The file is a module and the class names in the file are local.

// button.css
.button
.text
.subtext
// headerQuote.css
.quote
.text
.logo
.forbes

In the post-processing step, replace class names in the CSS file to guarantee uniqueness on a global scope. Prefixes are a part of md5 file checksum.

// button.css
.ce5_button
.ce5_text
.ce5_subtext
// headerQuote.css
.3d3_quote
.3d3_text
.3d3_logo
.3d3_forbes

Original and processed class names collections:

var button = {
button: ".ce5_button",
text: ".ce5_text",
subtext: ".ce5_subtext"
}
var headerQuote = {
quote: ".3d3_quote",
text: ".3d3_text",
logo: ".3d3_logo",
forbes: ".3d3_forbes"
}

The HTML will look somewhat like this:

<div class="{{button.button}}">
<span class="{{button.text}}">Get Grammarly</span>
<span class="{{button.subtext}}">It's free</span>
</div>
<div class="{{headerQuote.quote}}">
<h2 class="{{headerQuote.text}}">
— Grammarly quickly and easily makes your writing better.
</h2>
<div class="{{headerQuote.logo}} {{headerQuote.forbes}}"></div>
</div>

What a bright future. And it’s here!

Demo time

A working example and code are published to Github. It uses React, but anything else can be used for templates — Handlebars, Express, Jade, etc. The only requirement is the ability to pass an object to the template and use it for classNames. That’s it.

--

--