Tag: bem

Thoughts on modular CSS

Thoughts on modular CSS

There was a time when I always asked myself which level of specificity should I reach when writing my CSS code. It is so easy to nest selectors without touching the HTML markup, write top level selectors for things like ‘h2’ or ‘a’… And end up rewriting rules, re-rewriting, un-writing the rewritten…

The problem with CSS is that multiple rules can be applied to the same element. This is a problem because developers tend to write generic rules and because some of the CSS properties are inherited till the infinity and beyond. I learned from OOP (Java) that you have to use inheritance when the object that is inheriting the properties is-a parent object. This is CSS, so forget those semantical nuances; if your parent has ‘Lato’ font, you have ‘Lato’ font. I do not mind if your parent is a Cat and you are a Ford Cortina.

In most of the situations, it is a good idea to:

  • Scope or namespace your selectors to reduce the specifity (BEM)
  • Bind your styles to classes and not to HTML tags, to avoid polluting the tags in all your application with styles that are tied only to a specific component (Opt-in Typography)

BEM (block__element–modifier)

This naming convention will help you to set a very low level specificity in your selectors while communicating the HTML structure of your components by simply looking at the CSS.

<!-- CLASSIC STYLING -->

<section class="avatar">

<img src="avatar.jpg">

<span>KoolUsername99</span>

</section>



<style>

.avatar { } /* Specificity of 10 */

.avatar img { } /* Specificity of 11 */

.avatar span { } /* Specificity of 11 */

</style>

This is good… to an extent. As the SaSS documents say “Be aware that overly nested rules will result in over-qualified CSS that could prove hard to maintain and is generally considered bad practice“.

In modular applications, this works better:

<!-- BEM STYLING -->

<section class="avatar">

<img class="avatar__img" src="avatar .jpg">

<span class="avatar__span">KoolUsername99</span>

</section>



<style>

.avatar { } /* Specificity of 10 */

.avatar __img { } /* Specificity of 10 */

.avatar __span { } /* Specificity of 10 */

</style>

Looks verbose, but ends up being much more maintainable and clearer.

Opt-in Typography

This is a simple idea took from a Chris Eppstein (core team of SaSS) talk. Instead setting global styles for typographic elements like h1, he proposes to apply those styles as a class (.h1 or .title) to avoid tying presentation to the base tags.