Skip to main content

Learn

HTML vs CSS

Game

BEM Methodology

GetBEM

BEM stands for Block, Element, Modifier. It's a popular naming convention for CSS classes that aims to make front-end code more readable, maintainable, and scalable. The BEM methodology helps create reusable components and promotes a modular structure in your CSS.

Here's a breakdown of the three main concepts in BEM:

Block: A block is a standalone component that is meaningful on its own. It's the root of an independent entity and can be reused across your project. Examples of blocks could be header, menu, button, or card.

Element: An element is a part of a block that has no standalone meaning and is semantically tied to its block. Elements are denoted by two underscores (__) following the block name. For example, menu__item, card__title, or button__icon.

Modifier: A modifier is used to change the appearance, behavior, or state of a block or element. Modifiers are denoted by two hyphens (--) and can be attached to blocks or elements. For example, button--large, menu__item--active, or card--featured.

The BEM naming convention follows this pattern:

block__element--modifier

Here's an example of how you might use BEM in your HTML and CSS:

<nav class="menu">
<ul class="menu__list">
<li class="menu__item">
<a href="#" class="menu__link menu__link--active">Home</a>
</li>
<li class="menu__item">
<a href="#" class="menu__link">About</a>
</li>
</ul>
</nav>
.menu { /* styles for the menu block */ }
.menu__list { /* styles for the list element */ }
.menu__item { /* styles for the item element */ }
.menu__link { /* styles for the link element */ }
.menu__link--active { /* modifier for active link */ }

Benefits of using BEM:

Modularity: Each block is independent, making it easy to reuse across different projects.

Clarity: The naming convention makes it clear which elements belong to which block and what their purpose is.

Specificity: BEM reduces CSS specificity issues by keeping selectors flat and avoiding nesting.

Scalability: As projects grow, BEM helps maintain a clear structure and prevents CSS conflicts.

While BEM can lead to longer class names, the benefits in terms of code organization and maintainability often outweigh this drawback, especially in larger projects or when working in teams.

Remember, BEM is just one of several CSS methodologies, and while it's widely used, the best approach depends on your project's specific needs and your team's preferences.