Ampersand (&) in SASS Selectors: Usages and Workarounds
SASS, a preprocessing language for CSS, utilizes an ampersand (&) symbol to represent the parent selector, allowing for reusable and maintainable code. However, using the ampersand at the end or as part of a selector can pose challenges.
Problem Overview
A mixin intended to mimic LESS behavior has a selector with an ampersand (&) at the end, causing incorrect output. The desired result is to generate a nested set of selectors where the caller class is added to each subsequent level, as shown below:
.callerClass .foreverAlone{ ... } .callerClass .iThink .illNeverWork.callerClass{ color: $pinkUnicornRainbow; ... }
Solutions
For Sass versions 3.2 and below, valid ways to use the parent selector include:
&, &.bar, &#bar, &:after, &[active]
In Sass 3.3, the following syntax is added:
&bar, &-bar
Sass 3.4 introduces a new feature where the ampersand can be assigned to a variable and used within an @at-root rule:
$foo: &;
@at-root bar#{&} { color: red; }
Application to Problem
To address the given mixin, the ampersand should be used in conjunction with the caller class as follows:
@mixin button-variant($color, $background, $border) { ... .callerClass&.foreverAlone{ ... } .callerClass&.iThink .illNeverWork.callerClass& { color: $pinkUnicornRainbow; ... } }
The above is the detailed content of How to Use the Ampersand (&) in SASS Selectors: Solving Nesting Challenges with Mixins. For more information, please follow other related articles on the PHP Chinese website!