liveBook · Manning

BEM element

As explained in CSS in Depth, Second Edition

A BEM element is a child or descendant part of a block identified by a class combining the block name with a double underscore.

A BEM element names a child or occasional grandchild of a block with the block name, a double underscore, and the element name. Names such as media__image and media__body reveal both the element’s role and its module. section 9.1.3

Use BEM element names to keep module styles explicit without relying heavily on descendant selectors:

  • Give the main module a descriptive block class, such as media. section 9.1.4
  • Name its parts media__image and media__body; the block name already makes these classes unique, so .media > .media__image is usually unnecessary. section 9.1.4
  • Choose an element class when its semantic role or markup must remain flexible; targeting .media__title permits different heading levels, whereas targeting h4 imposes a restriction. section 9.1.4
  • Avoid encoding every nesting level by default: media__body__title may describe hierarchy, but a direct element class is often sufficient. section 9.1.4

A media module

Pair a block with independently named parts: <div class="media"><img class="media__image" ...><div class="media__body"><h4>Strength</h4><p>Strength training is an important part of injury prevention.</p></div></div>. The image and body can be styled directly, while the body’s heading can use .media__body > h4 when that heading choice is intentional. section 9.1.4

Listing 9.8 Media module with subelements
@layer modules {
  .media {        #1
    display: flex;
    gap: 1.5em;
    padding: 1.5rem;
    background-color: #eee;
    border-radius: 5px;
  }

  .media__image {         #2
    align-self: start;
  }

  .media__body {         #2
    overflow: auto;
    margin-block-start: 0;
  }

  .media__body > h4 {     #3
    margin-block-start: 0;
    color: #333;
  }
}

Inspect the complete CSS for the media block, image element, body element, and body heading. section 9.1.4

How CSS in Depth, Second Edition covers it

How deep it goes
Explains naming, selector choices, nesting trade-offs, and a complete media-module implementation.
Examples
Uses the media module with media__image, media__body, and a heading inside the body.
What it assumes
Assumes familiarity with CSS classes and selectors while defining block, element, and modifier terminology.
What you can do after
Apply BEM naming to build multi-element modules with explicit, reusable selectors.
How it connects
Connects BEM elements with blocks, modifiers, descendant selectors, and modular CSS.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of CSS in Depth, Second Edition. The section links point to the parts of the book it draws on.