Performance: Combining & with BEM naming
This affects CSS selector matching speed and rendering performance by how selectors are combined and scoped.
.block { &__element { color: red; } &__element--modifier { color: blue; } }
.block__element { color: red; } .block__element--modifier { color: blue; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Repeated full BEM selectors | No extra DOM nodes | 0 | Low but slower style matching | [X] Bad |
| Nested & with BEM selectors | No extra DOM nodes | 0 | Low and faster style matching | [OK] Good |
& symbol represent when used in Sass with BEM naming?& in Sass& symbol in Sass means "use the current parent selector" inside nested rules.&__element or &--modifier appends to the parent block's class name.& = current parent selector [OK]& to create a BEM modifier for a block named .card?--modifier, so &--active appends --active to the parent block.&. &__active { background: green; } uses __ which is for elements, not modifiers. &-active { background: green; } uses a single dash, which is incorrect for BEM modifiers..button {
color: blue;
&__icon {
margin-right: 0.5rem;
}
&--large {
font-size: 2rem;
}
}& appends to the parent selector .button. So &__icon becomes .button__icon and &--large becomes .button--large..button, .button__icon, and .button--large with their respective styles..menu {
&__item {
color: black;
}
&-active {
font-weight: bold;
}
}--, so &-active is incorrect; it should be &--active.&__item is correct for elements, so no error there..profile with an element avatar and a modifier highlighted. Which Sass code correctly combines & with BEM naming to style both the element and modifier inside .profile?__, so &__avatar correctly targets .profile__avatar.--, so &--highlighted correctly targets .profile--highlighted.Pass the test and this pattern moves unknown