Sub topic 4
Building components with BEM
This chapter assumes you know CSS selectors, specificity and the cascade, and that you can link stylesheets to HTML pages. The earlier chapters on naming conventions and on specificity cover the background. Here you will apply BEM to build components whose styles stay predictable as a codebase grows.
What BEM is
BEM stands for Block, Element, Modifier. It is a naming convention, not a tool or a library. Every class name encodes what a piece of markup is and how it relates to the component around it.
- A block is a standalone component that makes sense on its own, such as
card,menuorsearch-form. - An element is a part of a block that has no meaning outside it, such as a card's title. You write it as
block__element. - A modifier is a variation of a block or element in appearance or state, such as a featured card. You write it as
block--modifierorblock__element--modifier.
The two underscores separate a block from its element. The two hyphens separate an entity from its modifier. A single hyphen is only a word separator inside a name, so search-form__submit-button is one block, one element.
BEM solves two problems from the scaling chapters. The class name tells you where a rule belongs, so you can find it without searching. It also lets every rule use one class selector, which keeps specificity flat and uniform.
A first component
Start with the CSS. Each rule is a single class selector.
.card {
padding: 1rem;
border: 1px solid #ddd;
}
.card__title {
font-size: 1.25rem;
}
.card--featured {
border-color: gold;
}Now the markup. The block class and the modifier class sit together on the same element, and each inner element carries a class named after its block.
<article class="card card--featured">
<h2 class="card__title">Release notes</h2>
<p class="card__body">What changed this week.</p>
</article>Every selector has specificity 0,1,0. When two rules conflict, source order decides. That is why .card--featured must appear after .card in the file: both set border-related properties, and the later rule wins.
Why flat selectors matter
Compare BEM with a descendant-based approach:
.sidebar .card h2 {
font-size: 1rem;
}This rule has specificity 0,2,1. It depends on the card sitting inside a sidebar, and on the title being an h2. To override it elsewhere you need an equal or higher specificity, which pushes teams toward longer selectors and eventually !important.
With BEM you give the title a class and style that class. If a card in the sidebar needs a smaller title, add a modifier instead of a longer selector:
.card__title {
font-size: 1.25rem;
}
.card__title--compact {
font-size: 1rem;
}The relationship is now stated in the markup, not hidden in selector context. Moving the card to another page does not change how it looks.
Modifiers in practice
A modifier is always used alongside the base class, never instead of it. Write class="card card--featured", not class="card--featured". The base class supplies the shared styles. The modifier supplies only the differences.
Modifiers are often used for two kinds of variation:
- Appearance, such as
button--primaryorbutton--small. - State, such as
menu__item--active.
Some teams write modifiers as key-value pairs, for example button--size-small or button--theme-dark. This is part of the original BEM style and helps when a component has several independent dimensions. Pick one form and keep it across the codebase.
Design elements as parts, not as nesting
The most common BEM error is mirroring the DOM depth in the class name. Suppose a card contains a header, and the header contains a title.
<!-- Avoid -->
<article class="card">
<header class="card__header">
<h2 class="card__header__title">Release notes</h2>
</header>
</article>card__header__title is not valid BEM. An element belongs to a block, not to another element. The corrected markup flattens the names:
<article class="card">
<header class="card__header">
<h2 class="card__title">Release notes</h2>
</header>
</article>If the markup structure changes later, for example you remove the header wrapper, the class names remain valid. The names describe ownership, not position.
When a part becomes its own block
Sometimes an element grows complex enough to deserve its own identity. A card might contain an author byline with an avatar, a name and a date. Keep it as card__byline while it only makes sense inside the card. Promote it to a block named byline when you want to reuse it elsewhere or when it has elements and modifiers of its own.
Two questions help decide:
- Would this part make sense on a page without the parent block?
- Do you want to style or reuse it independently?
If the answer to either is yes, make it a block.
Mixes: combining a block and an element
A mix applies a block class and another block's element class to the same node. This lets a component be positioned by its parent without the parent reaching into its internals.
<div class="card">
<button class="button button--primary card__action">Read more</button>
</div>button and button--primary define what the button looks like. card__action defines where it sits in the card, for example margin-top: auto. Neither block needs to know the other's inner details. Resist the urge to write .card .button instead. That reintroduces the context-dependent selector BEM avoids.
Writing BEM with a preprocessor
In Sass, the & parent selector can build the suffix, which saves typing. The output is still flat.
.card {
padding: 1rem;
&__title {
font-size: 1.25rem;
}
&--featured {
border-color: gold;
}
}This compiles to .card, .card__title and .card--featured. Native CSS nesting does not support this. In plain CSS, &__title is not valid because & is not string concatenation. Inside a native nested rule you would write the full class name, or keep the rules at the top level.
A gotcha with the Sass form: searching your codebase for card__title finds nothing in the source file. Teams that value searchability often write the full class names, even in Sass.
BEM with tokens and layers
BEM controls selector shape. It does not control values or order, so it combines well with other tools in this tutorial.
- Design tokens. Use custom properties for colours and spacing inside BEM rules, as in
border-color: var(--color-accent), so a theme change touches one place. - Cascade layers. Put BEM components in a
componentslayer. A utility layer declared after it wins over components regardless of specificity. - Linting. Enforce the naming pattern automatically, as shown next.
Enforcing the convention with Stylelint
Naming conventions drift unless a tool checks them. The standard Stylelint preset requires kebab-case class names, which rejects __ and --. You must override selector-class-pattern to accept BEM.
{
"extends": "stylelint-config-standard",
"rules": {
"selector-class-pattern": [
"^[a-z][a-z0-9]*(-[a-z0-9]+)*(__[a-z0-9]+(-[a-z0-9]+)*)?(--[a-z0-9]+(-[a-z0-9]+)*)?$",
{
"message": "Use BEM: block, block__element, block--modifier"
}
],
"selector-max-id": 0,
"selector-max-specificity": "0,2,0",
"declaration-no-important": true
}
}The pattern accepts card, card__title, card--featured and card__title--compact. It rejects card__title__text, Card and card_title. The specificity limit of 0,2,0 still allows a state selector such as .menu__item:hover, which is 0,2,0, but blocks selectors with type or ID parts.
Common errors
| Error | Example | Fix |
|---|---|---|
| Element of an element | `card__header__title` | Use `card__title` |
| Modifier without base class | `class="card--featured"` | Use `class="card card--featured"` |
| Descendant selector on blocks | `.sidebar .card` | Add a modifier or a mix |
| Qualifying with a tag | `h2.card__title` | Use `.card__title` |
| Styling an element outside its block | `.card__title` in markup with no `.card` ancestor | Keep elements inside their block |
| Wrong source order | `.card--featured` placed before `.card` | Put modifiers after the base rule |
Where BEM falls short
BEM has costs, and you should weigh them against other options.
- Long class names. Markup gets verbose. This is a trade-off for clarity.
- Discipline, not enforcement. Nothing in CSS stops two teams from creating a block called
card. Class names are still global. For true isolation, consider the scoping techniques in a later chapter, such as CSS Modules or@scope. - Overrides between blocks. Changing one block's look inside another still needs a mix or a modifier. This is deliberate, but it means more upfront design of the component's API.
BEM works best with a team that agrees on it, a linter that checks it and a file layout that puts one block in each file.
Exercise
A teammate writes <div class="card__header__title"> and the rule .sidebar .card__title { font-size: 1rem; }. Describe two problems with this approach and rewrite both so that cards in a sidebar have a smaller title.
Show answer
First, card__header__title is an element of an element, which BEM does not allow. Elements belong to the block, so the name should be card__title. Second, .sidebar .card__title has specificity 0,2,0 and ties the style to the sidebar, so it is harder to override and breaks when the card moves. Use a modifier instead: add card__title--compact to the title in the sidebar and write .card__title--compact { font-size: 1rem; } after the .card__title rule. The markup becomes <h2 class="card__title card__title--compact"> and every selector has specificity 0,1,0.
Exercise
Why does the standard Stylelint preset reject the class name card__title, and which rule do you change to accept it?
Show answer
The preset sets selector-class-pattern to require kebab-case, and a name containing __ does not match it. Override selector-class-pattern with a regular expression that allows an optional __element and an optional --modifier after the block name.