A Simple Guide to Using BEM Naming in CSS

BEM helps us name CSS classes in a way that makes our code easy to read and use. BEM stands for Block, Element, Modifier. Let’s learn what each of these means.

What is BEM?

  • Block: A big part of the page that can stand alone (like button, header, container).
  • Element: A smaller part inside a block (like button__icon, header__title).
  • Modifier: A way to change the look or behavior of a block or element (like button--primary, header__title--large).

BEM Syntax

BEM uses a specific way to name things:

  • Block: block-name
  • Element: block-name__element-name
  • Modifier: block-name--modifier-name or block-name__element-name--modifier-name

Examples

  1. block
HTML
<div class="menu"></div>
CSS
.menu {
    /* styles for the menu block */
}

2. Element

HTML
<div class="menu">
    <div class="menu__item"></div>
</div>
CSS
.menu__item {
    /* styles for the menu item element */
}

Modifer

HTML
<div class="menu menu--large">
    <div class="menu__item menu__item--active"></div>
</div>
CSS
.menu--large {
    /* styles for the large menu modifier */
}

.menu__item--active {
    /* styles for the active menu item modifier */
}

Why Use BEM?

  • Readability: Names tell you exactly what each part is and does.
  • Maintainability: Easy to update and manage styles.
  • Scalability: Avoids name conflicts and keeps things consistent.

Practical Tips

  1. Stick to Consistent Naming: Always follow BEM syntax rules.
  2. Use Meaningful Names: Names should show the purpose of each block, element, or modifier.
  3. Avoid Over-Nesting: Keep the structure simple.
  4. Use BEM with Preprocessors: Works well with tools like Sass or LESS.

Conclusion

Using BEM in your CSS makes your code easy to understand and manage. Follow the simple rules of blocks, elements, and modifiers to make your stylesheets clear and organized. Happy coding!

Feel free to adjust this guide as needed.