Introduction
BEM (Block, Element, Modifier) is a CSS methodology that helps create scalable, maintainable, and reusable code by following a structured naming convention.
1. What is BEM?
BEM divides UI components into three categories:
- Block: The main component (e.g.,
.button
) - Element: A part of the block (e.g.,
.button__icon
) - Modifier: A variation of the block/element (e.g.,
.button--large
)
Example:
<button class="button button--primary">
<span class="button__icon"></span>
Click Me
</button>
HTML2. BEM Naming Convention
.block { }
.block__element { }
.block--modifier { }
CSSExample:
.card {
background: #fff;
}
.card__title {
font-size: 20px;
}
.card--highlighted {
border: 2px solid red;
}
CSS3. Benefits of BEM
- Scalability: Clear structure for large projects.
- Reusability: Modular approach to CSS.
- Maintainability: Easy to understand and modify.
- No Conflicts: Avoids style overrides.
4. BEM in Action
Example Component:
<div class="navbar navbar--dark">
<div class="navbar__logo">Brand</div>
<ul class="navbar__menu">
<li class="navbar__item navbar__item--active">Home</li>
<li class="navbar__item">About</li>
</ul>
</div>
HTML.navbar {
display: flex;
justify-content: space-between;
}
.navbar__menu {
list-style: none;
}
.navbar__item--active {
font-weight: bold;
}
CSSConclusion
BEM helps maintain clean, modular, and scalable stylesheets, making collaboration and maintenance easier in large projects.