0
0
SASSmarkup~5 mins

Combining & with BEM naming in SASS

Choose your learning style9 modes available
Introduction

Using & with BEM helps write cleaner CSS by nesting styles for blocks, elements, and modifiers together.

When you want to style a block and its elements in one place.
When you need to add a modifier style to a block or element.
When you want to keep your CSS organized and easy to read.
When you want to avoid repeating the full class names.
When you want to write less code but keep clear naming.
Syntax
SASS
.block {
  &__element {
    // styles for element
  }
  &--modifier {
    // styles for modifier
  }
}

The & symbol means "use the parent selector here".

BEM uses __ for elements and -- for modifiers.

Examples
This styles the button__icon element inside the button block.
SASS
.button {
  &__icon {
    color: blue;
  }
}
This styles the button--large modifier of the button block.
SASS
.button {
  &--large {
    font-size: 2rem;
  }
}
This styles both an element card__title and a modifier card--highlighted inside the card block.
SASS
.card {
  &__title {
    font-weight: bold;
  }
  &--highlighted {
    background: yellow;
  }
}
Sample Program

This example shows a menu block with items as elements and an active item as a modifier. The CSS uses BEM naming combined with & in Sass (shown here as compiled CSS) to style them clearly.

SASS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>BEM with & in Sass</title>
  <style>
    .menu {
      background: #eee;
      padding: 1rem;
    }
    .menu__item {
      color: #333;
      padding: 0.5rem;
    }
    .menu__item--active {
      color: white;
      background: #007acc;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <nav class="menu">
    <div class="menu__item">Home</div>
    <div class="menu__item menu__item--active">About</div>
    <div class="menu__item">Contact</div>
  </nav>
</body>
</html>
OutputSuccess
Important Notes

Remember to compile Sass to CSS before using it in the browser.

Using & keeps your styles connected to the parent block, making your CSS easier to maintain.

Summary

Combining & with BEM helps write neat, organized CSS.

Use &__element for elements and &--modifier for modifiers inside a block.

This method reduces repetition and keeps styles easy to find and update.