Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 39 ยท Real-world Patterns

BEM and Component Patterns in Sass

Write maintainable component styles with Sass: BEM with the & parent selector, @at-root, state classes, variant maps with @each, @content slots, and when to avoid nesting.

Most real-world Sass is component styling: a button, a card, a navigation bar. Components need predictable class names, a clean way to express variants (primary, danger, small) and states (hover, disabled, active), and a style that does not turn into five levels of nesting. This lesson combines a naming convention, BEM, with the Sass features that make it pleasant to write.

BEM in one minute

BEM stands for Block, Element, Modifier:

  • Block: a standalone component: .card
  • Element: a part of a block: .card__title (two underscores)
  • Modifier: a variation of a block or element: .card--featured (two hyphens)
HTML
<article class="card card--featured">
  <h2 class="card__title">Title</h2>
  <p class="card__text">Body</p>
</article>

Every class is one flat selector with the same low specificity, so overriding is predictable and there are no accidental clashes between components.

The parent selector & with suffixes

In Sass, & stands for the full parent selector, and you can append text to it. That is exactly what BEM needs:

SCSS
.card {
  padding: 1rem;
  border: 1px solid #ddd;

  &__title { font-size: 1.25rem; }    // .card__title
  &__text  { color: #555; }           // .card__text
  &--featured { border-color: gold; } // .card--featured
}

The compiled CSS has flat selectors, no .card .card__title. You get BEM's flat output with the grouping of nested source. Because &__title is a suffix on the parent, you cannot search for the final class name by grepping the source (card__title never appears). Some teams accept this; others prefer to write full names with @at-root.

Modifiers on elements and context

Often an element depends on a block modifier:

SCSS
.card {
  &__title { font-size: 1.25rem; }

  &--featured {
    border-color: gold;
    .card__title { color: darkgoldenrod; }    // writes .card--featured .card__title
  }
}

Using the full class name (.card__title) there is clear and works. When you want the reverse, "title inside a featured card" written next to the title, use & in a different position, with a selector like .card--featured &:

SCSS
.card {
  &__title {
    font-size: 1.25rem;

    .card--featured & { color: darkgoldenrod; }   // .card--featured .card__title
  }
}

The & at the end places the parent where you wrote it. This "reverse nesting" keeps every rule about the title in one place.

BEM with &

@at-root: escape the nesting

Inside a nested rule everything is prefixed with the parent. @at-root puts a rule at the root of the stylesheet instead, which is how you write a flat BEM block with its related selectors without a prefix, or write a rule for something unrelated:

SCSS
.card {
  @at-root .no-js & { display: block; }   // .no-js .card

  @at-root #{&}__title { font-size: 1rem; }  // .card__title (full name via interpolation)
}

#{&}__title writes the parent selector with interpolation, so the output name is complete. It also works when the parent is a list or has pseudo-classes, where &__title would be an error. Use @at-root sparingly: it is a tool for special cases, not the default.

State classes and pseudo-classes

Combine state with the component using &:

SCSS
.button {
  background: #4f46e5;
  color: white;

  &:hover { background: #4338ca; }
  &:focus-visible { outline: 3px solid #a5b4fc; outline-offset: 2px; }
  &:disabled,
  &.is-disabled { opacity: 0.5; cursor: not-allowed; }
  &.is-loading { pointer-events: none; }
}

State classes (is-active, has-error) are set by JavaScript and describe current condition; modifiers (--large) describe permanent variation. Keeping them separate avoids a menu of ambiguous class names.

Variants with a map and @each

Do not copy a rule for every variant. Describe the differences as data:

SCSS
@use "sass:color";

$variants: (
  primary: #4f46e5,
  success: #15803d,
  danger: #b91c1c,
);

.button {
  padding: 0.5rem 1rem;
  border: 0;
  border-radius: 6px;
  color: white;

  @each $name, $bg in $variants {
    &--#{$name} {
      background: $bg;
      &:hover { background: color.adjust($bg, $lightness: -8%); }
    }
  }
}

Adding a fourth variant is one line in the map. The interpolation &--#{$name} builds .button--primary and friends.

Variants from a map

Slots with @content

A mixin can wrap caller-provided rules in a context, a good fit for state or media wrappers:

SCSS
@mixin when-focus {
  &:hover,
  &:focus-visible { @content; }
}

.link {
  color: #2563eb;
  @include when-focus { text-decoration: underline; }
}

You can also pass arguments back to the block with @include foo using ($x) { ... } and @content($x), useful for mixins that generate several rules and let the caller customize each.

SCSS
@mixin each-breakpoint($names...) {
  @each $name in $names {
    &-#{$name} { @content($name); }
  }
}

Extend and placeholders versus mixins

@extend makes one selector share another's styles by adding the selector to the original rule:

SCSS
%panel { padding: 1rem; border-radius: 8px; background: white; }
.card  { @extend %panel; }
.modal { @extend %panel; }

Output: .card, .modal { padding: 1rem; ... }. This produces compact CSS for truly identical rules. But @extend has costs: it cannot be used across @media boundaries, it can create very long selector lists, and it changes source order in confusing ways. A mixin copies declarations, which gzip compresses very well. Prefer mixins as the default; use placeholders for a small set of constant style bundles.

Design the component API with CSS custom properties

When a component has many knobs, expose a few custom properties as its public API instead of a pile of modifiers:

SCSS
.avatar {
  --avatar-size: 2.5rem;
  --avatar-ring: transparent;

  width: var(--avatar-size);
  height: var(--avatar-size);
  box-shadow: 0 0 0 3px var(--avatar-ring);
  border-radius: 50%;
}

Consumers write style="--avatar-size: 4rem" or .profile .avatar { --avatar-size: 6rem; } without needing a new modifier class for each size.

Keep nesting shallow

Nesting is convenient but easily abused. Each level lengthens the selector, raises specificity and couples styles to markup:

SCSS
// Hard to override and tied to the exact HTML
.nav { ul { li { a { span { color: red; } } } } }

Guidelines:

  • Three levels deep at most, and & modifiers and pseudo-classes do not count as another structural level.
  • Do not nest element tags inside components; give the element a class instead.
  • If you need to read the compiled selector to understand your own source, it is too deep.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What CSS does .card { &__title { color: red; } } produce?

    & is replaced by the parent selector and the suffix is appended, giving a flat .card__title.
  2. 2. What does .card--featured & { ... } written inside &__title compile to?

    The ampersand is placed where you wrote it, so the parent selector follows the .card--featured context.
  3. 3. Why prefer a mixin to @extend for shared declarations by default?

    Mixins are predictable; extend has side effects on selector lists and source order.
  4. 4. Which is better as a state, not a modifier?

    State classes like is-loading describe the current condition and are toggled by JavaScript.
  5. 5. What is @at-root used for?

    @at-root prevents the parent selector from being prepended.

Summary

  • BEM gives flat, low-specificity, predictable class names; &__element and &--modifier write them with grouped source.
  • Put & after a context selector (.theme-dark &) to keep all rules for an element together.
  • Describe variants as data in maps and generate them with @each.
  • Use @content for slot-like mixins; prefer mixins over @extend unless the rules are constant.
  • Expose custom properties as a component API and keep nesting to about three levels.

Next: Utility Class Generators