Why you should use BEM to organize your CSS

Chip Lempke
2 min readSep 20, 2021

--

If you’ve created a small app or simple webpage, how you organize your stylesheet isn’t very important. For much larger more complicated projects how you organize your code can impact the efficiency of the project. Not only does it affect how much code you have to write, it affects how much writing will be required. In addition, it can increase the amount of loading required by your browser which in turn impacts performance.

Why BEM?

BEM provides structure, which benefits any project, regardless of size. BEM, for me, is easy to understand and implement. It also avoids inheritance and reduces style conflicts.

The reason I choose BEM over other methodologies comes down to this: it is less confusing than the other methods (i.e. SMACSS) but still provides us the good architecture we want (i.e. OOCSS) and with a recognizable terminology.

Mark McDonnell

Block, Element, and Modifier

BEM stands for ‘block’, ‘element’, and ‘modifier’

Green = Block, Blue = Element, Red = Modifier

Block

Standalone entity that is meaningful on its own.

Examples:header, container, menu, checkbox, inputHTML<div class="block">...</div>CSS.block { color: #fff; }

Element

A part of a block that has no standalone meaning and is semantically tied to its block. The CSS class uses the name of the block followed by two underscores __ and the name of the element.

Examples:menu item, list item, checkbox caption, header titleHTML<div class="block">
...
<span class="block__elem"></span>
</div>
CSS.block { color: #fff; }
.block__elem { color: #303030; }

Modifier

A flag on a block or element. Use them to change appearance or behavior. The CSS class uses the name of the block or element followed by two dashes -- and the name of the modifier.

Examples:disabled, highlighted, checked, fixed, size big, color yellowHTML<div class="block block--mod">...</div>
<div class="block block--size-big block--shadow-yes">...</div>
CSS.block { color: #fff; }
.block--mod .block__elem { color: #303030}
.block__elem--mod { color: red}

There are only two hard problems in Computer Science: cache invalidation and naming things — Phil Karlton

Benefits

Structure

BEM makes your CSS easy to read and quick to navigate.

Modularity

BEM handles some of the issues with the cascading effect of the style sheet; because a block’s style isn’t dependent on other page elements, like if your h2 selector has unintended effects on sidebar’s h2.

Reusability

Creating blocks of code that are independent from each other allows you to reuse them, which will reduce the amount CSS you need to write. Blocks can become so reusable that you can build a library of them for later use.

--

--

No responses yet