
How to Nest to Grandparent Class in Sass
May 24, 2017
The Ampersand in Sass is very useful, especially when using something like BEM syntax. It outputs the immediate parent class of the current element.
.block {
border: 1px solid darkgray;
&__content {
background: white;
}
&__title {
color: blue;
}
&__footer {
background: gray;
}
}
This code outputs the following:
.block {
border: 1px solid darkgray;
}
.block__content {
background: white;
}
.block__title {
color: blue;
}
.block__footer {
background: gray;
}
But what if we want to select the grandparent class, not the immidiate parent? In the following example we want the
.block__title
to turn red when the user hovers over the .content
element:
.block {
border: 1px solid darkgray;
&__content {
background: white;
&:hover &__title {
color: red;
}
}
&__title {
color: blue;
}
}
The output code is not what we really want:
.block {
border: 1px solid darkgray;
}
.block__content {
background: white;
}
.block__content:hover .block__content__title {
color: red;
}
.block__title {
color: blue;
}
What we want is to output
.block__content:hover .block__title
. Sass does not let us do that with its built-in tools, but we can do something else – use variables.
.block {
$blockClass: &;
}
Now the variable $blockClass
is set to .block
and we can reuse its value further.
.block {
$blockClass: &;
border: 1px solid darkgray;
&__content {
background: white;
&:hover #{$blockClass}__title {
color: red;
}
}
&__title {
color: blue;
}
}
#{$blockClass}
just outputs the value of $blockClass
variable.
.block {
border: 1px solid darkgray;
}
.block__content {
background: white;
}
.block__content:hover .block__title {
color: red;
}
.block__title {
color: blue;
}
Hey psst, subscribe to my telegram channel, where I post tips and ideas for designers and developers.