'SCSS Nesting and extend

When I do a yarn build of the scss below I can only see the .select-list__item:hover in the compiled css, I am not seeing anything else from the class such as .select-list__item--selected I am not sure what the issue here is.

%select-list__item {   

&:hover {
    background: red;      
}

&--selected,
&--selected:nth-child(2n),
&--selected:hover {
    background: #00FF00;
 
}}


.select-list__item {
@extend %select-list__item;}


Solution 1:[1]

I believe it is to do with how placeholders (ie: %chosen-name) are meant to be used.

Although this is not explicitly pointed out in the documentation they are meant to be small bits that are reusable.

At my company, we use one for our generic button styles (margin, padding, font) and we extend that into all of our buttons (primary, secondary, tertiary).

A potential solution for your use case:

%select-list__item {   

    &:hover {
        background: red;      
    }
    
    &:focus{
        background: blue;
    }
    
}


.select-list__item {
    @extend %select-list__item;
    
    &--selected,
    &--selected:nth-child(2n),
    &--selected:hover {
        background: #00FF00;
    }
}

Or here's another - bit of an OTT solution for the example but you get the idea:


%select-list__item {   

    &:hover {
        background: red;      
    }
    
    &:focus{
        background: blue;
    }
    
}

%selected-list__item {
    background: #00FF00;
    &:nth-child(2n),
    &:hover {
        background: #00FF00;
    }
}

.select-list__item {
    @extend %select-list__item;
    
    &--selected {
        @extend %selected-list__item
    }
    
}

Solution 2:[2]

According to the documentation:

Extends are resolved after the rest of your stylesheet is compiled. In particular, it happens after parent selectors are resolved. This means that if you @extend .error, it won’t affect the inner selector in .error { &__icon { ... } }. It also means that parent selectors in SassScript can’t see the results of extend.

A mixin would work in your situation:

@mixin select-list__item() {   
  &:hover {
    background: red;      
  }
    
  &--selected,
  &--selected:nth-child(2n),
  &--selected:hover {
    background: #00FF00; 
  }
}

.select-list__item {
  @include select-list__item;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ben S
Solution 2 Arkellys