Yeldar Kurmangaliyev Yeldar Kurmangaliyev - 4 months ago 19
Sass (Sass) Question

How to reference SCSS sibling?

Assuming that I have the following HTML:

<div class="navigation__item">
<span class="navigation__item__icon"></span>
</div>


I want to apply some rules to an icon, when hovering an item, which can be described with the following CSS:

.navigation__item__icon {
color: black;
}

.navigation__item:hover .navigation__item__icon {
color: white;
}


I can achieve this using the following SCSS:

.navigation__item {
&:hover {
.navigation__item__icon { <-- here
color: white;
}
}

&__icon {
color: black;
}
}


Here, is there any way to avoid writing
navigation__item
? Something like "parent rule \ element".
I like Sass for logical structure so that if I want to rename the whole
navigation
block with elements, I can simply change
navigation
class name in the root, and everything is renamed. This case breaks this advantage.

Update: Actually, I have found a way to do this without using {} braces.
&
can be repeated more than once:

.navigation__item {
&:hover &__icon {
color: white;
}

&__icon {
color: black;
}
}


It is great, but it doesn't make much sense if I have many rules and rules for
&:hover
itself. The question is still open - is this possible to access sibling element definition from within the {} block.

Answer

In Stylus there is a Partial reference but I don't know anything similar in SASS. One solution could be using a variable for the parent selector:

.navigation__item {
  $selector: &;
  &:hover {
    #{$selector}__icon {
      color: white;
    }
  }

  &__icon {
    color: black;
  }
}

Is usefull is you change navigation__item class for another.

EDIT: I had used a wrong example, it's OK now.

Comments