Academy / Advanced Level: HTML and CSS
CSS Architecture and Methodologies
BEM (Block Element Modifier) Methodology
BEM (Block Element Modifier) is one of the most popular CSS methodologies. It provides a clear, convention-based naming system for organizing CSS. The main idea behind BEM is to break down a UI into independent blocks and manage their styles based on their state and context.
BEM Naming Convention:
- Block: Represents a reusable component (e.g.,
header,nav,button). - Element: Represents a part of the block (e.g.,
header__logo,nav__item). - Modifier: Represents a variation of the block or element (e.g.,
button--primary,nav__item--active).
Example of BEM:
htmlCopy code<div class="card">
<div class="card__header">
<h2 class="card__title">Card Title</h2>
</div>
<div class="card__body">
<p class="card__text">This is a card description.</p>
</div>
<button class="button button--primary">Click Me</button>
</div>
Explanation:
- Block:
card,button - Element:
card__header,card__title,card__text - Modifier:
button--primary
In this example, each component is self-contained, making it easier to style and modify without affecting other parts of the project.
Key Benefits of BEM:
- Clarity: The naming convention is explicit, making it easy to understand the relationship between elements.
- Modularity: Components are self-contained and can be reused across the project.
- Avoids Specificity Issues: Because of the predictable structure, BEM helps avoid specificity wars.