Make BEM

BEM (Block, Element, Modifier) is a very useful methodology for writing maintainable, scalable CSS.

What is BEM (at a high level)

  • Block — an independent, reusable component. It should make sense on its own (e.g. menu, card, form).
  • Element — a part of a block that has no standalone meaning outside that block (e.g. menu__item, card__header).
  • Modifier — a flag that changes appearance, behavior, or state of a block or element (e.g. menu--horizontal, card__header--dark).

The BEM website gives the naming rules:

  • Block names: lowercase letters, digits, dashes (e.g. block-name)
  • Element: block__elem-name (double underscore)
  • Modifier: block--modifier or block__elem--modifier (double dash)

Simple example

Here’s a small example:

<div class="card card--featured">
  <h2 class="card__title">Title</h2>
  <p class="card__text">Some text content.</p>
  <button class="card__button card__button--disabled">Click me</button>
</div>

And CSS:

.card { /* base block styling */ }

.card--featured {
  border: 2px solid gold;
}

.card__title {
  font-size: 1.5em;
}

.card__text {
  color: #333;
}

.card__button {
  padding: 0.5em 1em;
}

.card__button--disabled {
  opacity: 0.5;
  pointer-events: none;
}
  • card is a block.
  • card__title, card__text, card__button are elements of the card block.
  • card--featured is a block-level modifier.
  • card__button--disabled is an element-level modifier.

Advantages

  • Clarity & consistency: You know exactly what class belongs where, reducing naming collisions or ambiguities.
  • Scoped styles: Because elements are tied to blocks, you avoid global CSS bleed.
  • Easier maintenance and updates: You can refactor, add modifiers, or reuse blocks confidently.
  • Better for component-based UI (React, Vue, etc.): Blocks map nicely to components.

Key Points

  • Blocks are classes on DOM nodes; they should not rely on tags or IDs in selector definitions. No styling via div.block, #block, or using descendant selectors that depend on structure.
  • Avoid coupling via structure in CSS. By avoiding selectors like .block .block__elem, you ensure that elements are always styled purely by their class, and not via indirect context. This helps make the CSS more modular and reusable.
  • Modifiers are extra classes, not replacements. You keep the base class and add the modifier class. (e.g. <div class="block block--mod">)
Principle Example Why
Don’t depend on parent structure .card .card__title Fragile — breaks if HTML changes
Don’t depend on tag type div.card__title Restrictive — can’t reuse with other tags
Depend only on class names .card__title Predictable, reusable, flat CSS