Reuse selector in SCSS as a suffix
How can I use the ampersand in SCSS to reuse the parent selector as a suffix?
I came from LESS CSS and am currently doing my first project in SCSS. In LESS, I can use an ampersand &
to refer to the parent selector anywhere in the selector. It seems to me that this operator has some quirks in SCSS.
Example:
.grid {
/* grid styles */
ul& {
/* grid styles if this class was set to an UL element */
}
}
In LESS CSS it compiles like this, and in most cases I need it:
.grid {
/* grid styles */
}
ul.grid {
/* grid styles if this class was set to an UL element */
}
But in SCSS this rules out. SCSS has another notation:
.grid {
/* grid styles */
ul#{&} {
/* using SCSS escaping syntax*/
}
}
But this again gives me an unexpected result:
.grid {
/* grid styles */
}
.grid ul.grid {
/* Uh SCCS, what happened now? */
}
Is there a way in SCSS to reuse a parent selector if it is not the first part of the selector ?
source to share
You can use a directive @at-root
to create a rule that is generated outside of its scope, but that retains the value of its parent ( &
)
.grid {
/* grid styles */
@at-root {
ul#{&} {
/* using SCSS escaping syntax*/
}
}
}
Output
.grid {
/* grid styles */
}
ul.grid {
/* using SCSS escaping syntax*/
}
Tested on sassmeister
More information on the SASS documentation page
source to share