2

I have a doubt of writing child selector when I have a hover event in parent.

say I have HTML like this,

<div class="root">
  <div class="root__element">
    <div class="root__sub-element" />
  </div>
</div>

In sass,

.root {
  $root: &;

  &__element {
    &:hover {
      #{$root}__sub-element {color: red;} // question comes here, why 
                                          // not using .root_sub-
                                          // element?
    }
  }
}

what I want is hover event happens in root__element, color change in root__sub-element. Should I use ampersand to keep SASS or I would directly use '.root__sub-element'?

Tenn
  • 21
  • 2

1 Answers1

0

You should Keep SASS.

  • I noticed you tagged 'bem' in your question.

  • As per BEM, your block element class to continue with your prefix of last child class. http://getbem.com/naming/

POINT 1:

If you have another element with the same behavior. the hardcoded class .root__sub-element will break. please consider the following sass code with multiple root classes.

SASS Code :

$roots: root, newroot;
@each $r in $roots {
  .#{$r}{
    $root: &;
    &__element {
      &:hover {
        #{$root}__sub-element {color: red;}
      }
    }
  }
}

POINT 2:

This is very rare or not suggested practice, but suppose in case your root block class .root changed to .newroot. as per bem, your child classes will change with new prefix. Here, hardcoded class .root__sub-element will break, you need to changes it to all area manually.

Otherwise:

CSS is:

.newroot__element:hover .root__sub-element {
  color: red;
}

Expected CSS:

.newroot__element:hover .newroot__sub-element {
  color: red;
}
Sachink
  • 1,425
  • 10
  • 22
  • Very nice explanation. In both scenario using variable is the only choice. BTW, I do use BEM in naming, but not very BEM-ish, cannot convince myself to use B__E__E__E__E--M :) – Tenn Mar 25 '18 at 14:11