How to actually implement BEM

MasaKudamatsu
Web Dev Survey from Kyoto
2 min readAug 9, 2018

I first heard about BEM from a CodeCademy reviewer who gave me feedback on my last project. She praised my coding style for HTML/CSS. As a means to take my coding to a next level, she suggested using BEM.

Image source

It was a bit tricky to figure out what BEM is about. But this article by Harry of CSS Wizardly back in 2013 has persuaded me of its value quite effectively.

Even more tricky, however, is to figure out how to actually implement BEM. After trial and error, this Quick Start guide turns out to be the most helpful.

There are three things that weren’t initially obvious to me but have turned out to be crucial to understand.

The first is the naming convention: the name of blocks and elements refers to their purpose while the name of modifiers describes their appearance (often CSS property values).

Second, when they say, “Blocks are independent while elements are dependent of their parent block,” it is not about the content but about the CSS styling. If CSS styling is independent of any other HTML tags, that’s for a block. Otherwise, it’s for an element.

Finally, we can give a block and an element of another block to the same HTML tag.

For the last two points, an example in this page is more helpful than the one in the Quick Start guide page. Let me also demonstrate these points with a different example.

We want to apply the same color and font-family property values to all headings on our page, but the font-size property should differ by whether it’s a section title h2 or a subsection title h3.

In this case, apply a block (say, called .heading) both to h2 and h3 for the color and font-family properties. But use an element (say, .section__title and .subsection__title) for the font-size.

This way, if we want to change the font-color property later, you can just look at the .heading selector. We don’t have to search over our CSS file for every single line of code that deals with font-color.

To sum up:

(1) Blocks and elements are for purposes while modifiers are for appearance;

(2) Blocks are for styles independent of any other HTML tags while an element’s style cannot be separated from other elements within the same block.

(3) One HTML tag can take both a block and an element of another block, to minimize the duplication of CSS lines of code.

--

--

MasaKudamatsu
Web Dev Survey from Kyoto

Self-taught web developer (currently in search of a job) whose portfolio is available at masakudamatsu.dev