Mikolaj Sitek
Mikolaj Sitek

Reputation: 23

SASS / SCSS hover when using &__* syntax to reach parent selector

Yes yes, I had a hard time trying to define my question.

The general case is like this: in sass/scss I have a button with some variants:

.button {
   /* generic button styles here */
   &__icon {
       color: green;
   }
}

And now I wish to use some hover styles on this, per variant. But because I use the &__* I can't seem to grasp how to do this without rewriting the parent class name.

.button {
   /* generic button styles here */
   &__icon {
       color: green;
   }
   &:hover {
       .button__icon {
           color: red;
       }
   }
}

^^ this works but is pretty manual

Is there a way in sass that allows to access the parent class and get something like:

&:hover {
    &__icon {
        color:red;
    }
}

But this time the &__icon should reference the parent.

The html to this would look somewhat like this:

<button type="button" class="button">
    [name]
    <span class="button__icon">+</span>
</button>

Upvotes: 2

Views: 12476

Answers (1)

mwl
mwl

Reputation: 1488

.button {
   $root: &;

   &__icon {
       color: green;
   }

   &:hover #{$root}__icon {
       color: red;
   }
}

or

.button {
   $root: &;

   &__icon {
       color: green;

       #{$root}:hover & {
           color: red;
       }
   }
}

Upvotes: 4

Related Questions