P
P
photosho2022-03-29 11:04:10
css
photosho, 2022-03-29 11:04:10

How to work with BEM and Sass in the case of nested elements?

How to make friends between BEM and Sass in the case of nested elements and the need to style according to a pseudo-class (for example, hover)? Here is an example situation:

<div class="block">
  <div class="block__element-1">
    <div class="block__element-2">
    </div>
  </div>
</div>

.block {
  &__element-2 {
    ...
  }
  
  &__element-1 {
    ...
    &:hover {
        /* Стили element-2 */
    }
  }
}


It turns out that inside the "hover" styles, you need to write the class name in full: ".block__element-2", and with increasing nesting, the situation is aggravated. If the name of the block changes, then it will need to be changed in all such places.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2022-03-29
@photosho

.block {
  &__element-2 {}
  &__element-1 {}
  &__element-1:hover &__element-2 {}
}

.block {
  $this: &;
  &__element-2 {}
  &__element-1 {
    &:hover #{$this}__element-2 {}
  }
}

and as the nesting increases, the situation worsens.

You don't need to increase nesting. This is contrary to the ideology of BEM.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question