BEM Architecture & Naming Conventions
As CSS codebases grow, maintaining predictability and preventing specificity conflicts become major engineering challenges. BEM (Block, Element, Modifier) is a battle-tested naming convention created to keep component CSS modular, flat, and scalable.
1. BEM Core Conceptsβ
BEM decomposes user interfaces into three distinct entities:
ββββββββββββββββββββββββββββββββββββββββββββββββ
β BLOCK β
β .card β
β βββββββββββββββββββββββββββββββ βββββββββββ β
β β ELEMENT β β
β β .card__title β β
β ββββββββββββββββββββββββββββββββββββββββββ β
β ββββββββββββββββββββββββββββββββββββββββββ β
β β MODIFIER β β
β β .card--featured β β
β ββββββββββββββββββββββββββββββββββββββββββ β
ββββββββββββββββββββββββββββββββββββββββββββββββ
- Block (
.block): A standalone, reusable component entity (e.g.,card,nav,button). - Element (
.block__element): A dependent sub-part of a block that has no standalone meaning outside of it, delineated by double underscores__(e.g.,card__title,nav__item). - Modifier (
.block--modifieror.block__element--modifier): A flag that alters the visual appearance, state, or behavior of a block or element, delineated by double hyphens--(e.g.,card--featured,button--large).
2. Specificity and the Flat Structure Advantageβ
Without BEM, developers often rely on deep structural nesting, leading to fragile specificity wars:
/* β Anti-Pattern: High Specificity & Fragile HTML Coupling */
div.sidebar ul.menu > li.item a {
color: #2563eb;
}
/* β
BEM Solution: Flat Single-Class Specificity (0,0,1,0) */
.menu__link {
color: #2563eb;
}
.menu__link--active {
color: #059669;
}
3. BEM Best Practices & Common Pitfallsβ
- Avoid Multi-Level Element Nesting: Avoid syntax like
.card__header__title. Keep element names shallow relative to the block (e.g.,.card__title). - Combine Block and Modifier Classes: Never use a modifier class in isolation. Always apply the base block/element class alongside its modifier (
class="btn btn--primary"). - Use Utility Classes Sparingly: Keep block styling encapsulated within the BEM scope to maintain predictability across teams.
Interactive Playground: BEM Notification Cardβ
Observe how BEM classes structure blocks, elements, and modifier states cleanly without specificity escalation:
Loading Interactive Editor...
Summary Reference Tableβ
| Entity | Syntax Pattern | Example Class | Purpose |
|---|---|---|---|
| Block | .block | .btn | Standalone UI block container |
| Element | .block__element | .btn__icon | Dependent sub-part of block |
| Modifier | .block--modifier | .btn--success | Variant style or state flag |