What is BEM?
BEM (Block-Element-Modifier) is a popular CSS naming methodology that helps create scalable, maintainable, and reusable components. It provides a clear structure for class names, making it easier for teams to collaborate and understand the relationship between HTML and CSS.
Core Concepts
| Concept | Syntax | Description | Example |
|---|---|---|---|
| Block | .block | Standalone component | .card, .button, .header |
| Element | .block__element | Part of a block | .card__title, .button__icon |
| Modifier | .block--modifier or .block__element--modifier | Variation or state | .button--primary, .card__title--large |
Blocks: Independent Components
Elements: Parts of Blocks
Modifiers: Variations & States
Complete Example
BEM with Preprocessors
Common Patterns
BEM File Structure
Mixing Blocks
BEM vs Other Methodologies
| Methodology | Naming Pattern | Pros | Cons |
|---|---|---|---|
| BEM | .block__element--modifier | Explicit, self-documenting, modular | Verbose class names |
| OOCSS | .object .child | Reusable objects, separation of structure/skin | Less explicit relationships |
| SMACSS | .l-header, .module | Categorization, flexible | Requires discipline |
| Atomic CSS | .w-50, .bg-red | Highly reusable, small CSS | Tight coupling to HTML, maintenance |
Best Practices
- Use descriptive names –
.user-cardnot.ucor.card1 - Avoid deep nesting – Keep elements flat (
.block__elementnot.block__element__subelement) - Use modifiers for variations – Not separate blocks
- Combine with utility classes – For spacing, typography utilities
- Be consistent – Same naming rules across entire project
- Document your components – Create a style guide/pattern library
- Use BEM with CSS-in-JS – Maintains naming consistency
- Never use IDs for styling – IDs break reusability and specificity
Common Mistakes
- Over-nesting elements –
.card__header__title__icon(too deep) - Inconsistent naming – Mixing
.card-title,.card__title,.CardTitle - Modifiers without base block – Missing
.buttonclass when using.button--primary - Styling based on parent context –
.sidebar .card(breaks encapsulation) - Using elements outside blocks – HTML structure must match BEM naming
- Overly generic names –
.box,.container,.wrapper
Real-World Project Example
Tools & Automation
BEM with React/Vue Components
Conclusion
BEM methodology provides a clear, scalable approach to CSS architecture. By using consistent naming patterns (Block__Element--Modifier), teams can build maintainable components that are reusable, self-documenting, and resistant to style conflicts. While class names become more verbose, the benefits of predictability and encapsulation far outweigh the costs for large-scale projects.