DEV Community

Cover image for BEM Methodology in CSS: predictable naming for clean styles
Naser Rasouli
Naser Rasouli

Posted on

BEM Methodology in CSS: predictable naming for clean styles

Why BEM?

As frontend projects grow, CSS quickly turns fragile—poor class names cause style collisions, debugging pain, and slow iteration. BEM gives you a predictable naming pattern so components stay isolated and easy to reason about.

What is BEM?

BEM stands for Block, Element, Modifier. Every class name reflects its role and state.

Core pieces

  • Block: A standalone UI piece with its own meaning and styles (card, navbar).
  • Element: A part of the block that relies on it; separated with __ (card__title).
  • Modifier: A variant or state of a block/element, marked with -- (card--featured, card__button--active).

Naming format

block
block__element
block--modifier
block__element--modifier
Enter fullscreen mode Exit fullscreen mode

Practical example

<div class="card card--featured">
  <h2 class="card__title">Card title</h2>
  <p class="card__description">Short description</p>
  <button class="card__button card__button--active">View</button>
</div>
Enter fullscreen mode Exit fullscreen mode
.card {
  display: grid;
  gap: 12px;
  padding: 16px;
  border: 1px solid #e0e0e0;
  border-radius: 10px;
}

.card--featured {
  border-color: #2563eb;
  box-shadow: 0 8px 24px rgba(37, 99, 235, 0.12);
}

.card__title {
  font-size: 1.1rem;
  margin: 0;
}

.card__description {
  margin: 0;
  color: #4b5563;
}

.card__button {
  justify-self: start;
  padding: 10px 14px;
  border-radius: 8px;
  background: #111827;
  color: #fff;
}

.card__button--active {
  background: #2563eb;
}
Enter fullscreen mode Exit fullscreen mode

Benefits of BEM

  • Clear readability—class names show role and state
  • Prevents style bleeding between components
  • Scales well for large, collaborative codebases
  • Easier debugging and tracing UI behavior
  • Encourages repeatable, stable UI patterns

Drawbacks and limits

  • Class names get longer
  • HTML can look busy in small projects
  • Requires team consistency; otherwise benefits disappear

When to use BEM

  • Medium/large projects with many shared components
  • Multi-person teams or codebases expected to grow
  • Component-based architectures (React, Vue, Angular, design systems)
  • When long-term maintenance matters

Quick usage tips

  • Pick meaningful, independent block names—not location-based (card over sidebar-card).
  • Avoid deep nesting in CSS; BEM naming reduces the need for it.
  • Modifiers should change state, not the fundamental structure of the block.

Takeaway

BEM’s predictable naming prevents CSS collisions and keeps styles maintainable. For teams and long-lived projects that value clean, extensible code, it’s a proven, low-friction pattern.

Top comments (0)