What is BEM

BEM — Block Element Modifierarrow-up-right is a methodology that helps us to create reusable code as a frontend developer.

Blocks, Elements & Modifiers

The standard naming for BEM takes the following structure

block__element--modifier

A block is always required and is the parent container. An element is a child of the block. A modifier can add styles to either a block or a block’s element.

Block

Standalone entity that is meaningful on its own. card header footer section container menu input

Element

A part of a block that has no standalone meaning and is semantically tied to its block. title item list checkbox caption

Modifier

A flag on a block or element. Use them to change behavior or appearance. disabled highlighted checked size color background-color

Advantages of BEM

  • Reusability: Composing independent blocks in different ways and reusing them intelligently reduces the amount of CSS code that you will have to maintain.

  • Structure: BEM methodology gives your CSS code a solid structure that remains simple and easy to understand.

  • Modularity Block styles are never dependent on other elements on a page, so you will never experience problems from cascading.

Prop

  • BEM avoids CSS conflicts by using unique contextual class names for every block, element, and modifier combination.

  • Browsers evaluate CSS selectors right to left and BEM encourages frontend developers to create a flat CSS structure with no nested selectors. So the less browsers have to evaluate, the faster they can render.

  • By avoiding the use of HTML element names in CSS selectors, BEM makes CSS code readily portable to a different HTML structure.

Cons

  • While the overall HTML code does ‘look’ ugly with BEM class names, the visitor of the website or application will not look in the source too often, so it is not really an issue.

  • It is known that BEM can bloat file sizes with the longer CSS class names, but this can easily be overcome by minifying and gzipping production code.

Alternatives

  • CSS modules

  • StyledComponents

  • CSS in JS

Last updated