Search code examples
htmlcsssassbem

Why is this SCSS selector not working


I have this HTML:

<div class="holder">
   <span class="holder__title">TITLE ONE</span>
</div>
<div class="holder">
   <span class="holder__title">TITLE TWO</span>
</div>
<div class="holder">
   <span class="holder__title">TITLE THREE</span>
</div>

Now, I want to modify TITLE TWO and TITLE THREE spans only and leave the first as it is, but I cannot get it to work. This is what I have tried:

.holder {
   &:not(:first-child) {
      &__title {
        display:none; // just to test
     }
  }
}

and

.holder {
  &:nth-child(n+2):nth-child(-n+3) {

    &__title {
      display:none; // just to test
    }
  }
}

It works ok in developer tools, but when I enter it in .scss file and compile nothings happens. Like selectors do not even get targeted.

How can I resolve this please?

Thank you.


Solution

  • & translates into existing selector at this exact point. Which means that this

    .holder {
       &:nth-child(n+2):nth-child(-n+3) {
         ...some-rule...
         &__title {
           ...other-rule...
         }
       }
     }
    

    translates into this CSS:

    .holder:nth-child(n+2):nth-child(-n+3) {
      ...some-rule...
    }
    .holder:nth-child(n+2):nth-child(-n+3)__title {
      ...other-rule...
    }
    

    If you're really keen on doing it properly, you should put .holder inside a variable, which doesn't break BEM (you're able to change it from only one place):

    $name: '.holder';
    #{$name} {
       &:nth-child(n+2):nth-child(-n+3) {
         ...some-rule...
         #{$name}__title {
           ...other-rule...
         }
     }
    

    which translates into this:

    .holder:nth-child(n+2):nth-child(-n+3) {
      ...some-rule...
    }
    .holder:nth-child(n+2):nth-child .holder__title {
      ...other-rule...
    }