What is BEM Methodology and How to Use It
BEM stands for Block, Element, Modifier, and it’s a popular naming convention and methodology for writing more structured and maintainable CSS and HTML. BEM was designed to bring clarity and consistency to the way developers create class names and structure their stylesheets, particularly for larger and more complex projects.
Here’s a breakdown of each component in the BEM methodology:
- Block: A self-contained component or module that represents a significant part of the user interface. Blocks are usually large, reusable sections of a webpage, like headers, footers, navigation bars, etc.
- Element: The components or parts that make up a block. Elements are nested within blocks and are not meaningful on their own. They are always prefixed with the block name, separated by a double underscore (
__
). - Modifier: Variations of a block or element’s state or appearance. Modifiers allow you to alter the style or behavior of a block or element without duplicating code. They are prefixed with the block or element name and are separated by a double hyphen (
--
).
Using BEM, class names are structured in a way that clearly indicates their purpose and relationship within the HTML structure. This approach reduces naming conflicts, enhances code readability, and makes it easier to understand the purpose of a class by just looking at its name.
Here’s an example of BEM in action:
HTML:
<div class="block"> <div class="block__element"></div> <div class="block__element block__element--modifier"></div> </div>
CSS (SCSS):
.block { // Block styles &__element { // Element styles } &__element--modifier { // Modifier styles } }
In this example, the “block” class represents a larger component, while “block__element” represents parts of that component. “block__element–modifier” applies a modifier to that element for specific styling variations.
BEM is not the only naming convention, but it’s widely adopted due to its clear structure and ability to scale with complex projects. It promotes a more systematic and organized approach to writing CSS and HTML, making it easier to collaborate, maintain, and extend codebases.