Skip to main content

CSS BEM: A Concise Overview of Block, Element, Modifier Methodology

BEM (Block, Element, Modifier) is a CSS naming convention that helps organize and structure CSS code for maintainability and reusability. It's based on the principle of separating the structure (block) from the presentation (element) and modifiers. This approach makes it easier to read, understand, and maintain complex CSS codebases.


The BEM Structure

The BEM structure consists of three parts:

  1. Block: Represents a standalone, reusable component or section.
  2. Element: Represents a child component or part of a block.
  3. Modifier: Represents a variation or state of a block or element.

BEM Naming Convention

BEM uses a specific naming convention to differentiate between blocks, elements, and modifiers:

Block: block-name

Element: block__element-name

Modifier: block--modifier-name or block__element--modifier-name


For example, consider a button component:

Block: button

Element: button__label (text inside the button)

Modifier: button--disabled (disabled button)


Using BEM in CSS

To apply BEM in CSS, simply use the appropriate class names for each block, element, and modifier. For example:

/* Block: Button */ .button { /* Styles for the entire button component */ } /* Element: Button label */ .button__label { /* Styles for the text inside the button */ } /* Modifier: Disabled button */ .button--disabled { /* Styles for a disabled button */ }

Advantages of BEM

BEM offers several advantages:

  • Improved readability: BEM's structured naming convention makes CSS code easier to read and understand, especially for large codebases.
  • Increased maintainability: By separating concerns and organizing code into logical units, BEM makes it easier to maintain and update CSS code.
  • Enhanced reusability: BEM promotes the reuse of blocks and elements, reducing code duplication and increasing efficiency.
  • Reduced specificity wars: BEM's naming convention helps prevent specificity conflicts, making it easier to override styles when needed.
  • Improved accessibility: BEM's structured approach can improve accessibility by ensuring that elements have unique class names, which assistive technologies can use for identification.

Conclusion

CSS BEM is a powerful naming convention that helps organize, structure, and maintain CSS code. By separating blocks from elements and modifiers, BEM promotes readability, reusability, and maintainability. Adopting BEM in your CSS workflow can significantly improve the quality and effectiveness of your codebase.

Comments

Archive

Show more

Topics

Show more