简体   繁体   中英

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.

& 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...
}

What you are trying to write is invalid SCSS. Remember, the & always refers to the parent selector when nesting.

So your SCSS

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

will translate to this CSS which is invalid:

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

A solution would be:

.holder {
   &:not(:first-child) {
      .holder__title {
        display:none;
     }
  }
}

Even though, this will break the BEM notation. Still, i will leave this here in case no better answer shows up.

A cleaner solution to use nested SCSS with a pseudo class like :not() without breaking BEM methodology would be:

.holder {
  $holder: &;

   &:not(:first-child) {
      #{$holder}__title {
        display:none;
     }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM