Home >Web Front-end >CSS Tutorial >How to Extend Parent Selectors in SASS Mixins When Using the Ampersand (&) at the End of a Selector?
Ampersand (&) in SASS Selectors: Extending Parent Scope
In SASS, the ampersand (&) symbol serves as a powerful tool for extending parent selectors. It allows you to nest rules within a mixin in a way that includes the parent selector's own class name. However, using the ampersand at the end of a selector presents a unique challenge.
The problem lies in ensuring that the selector includes the caller class name. Consider the following Sass mixin:
<code class="sass">@mixin button-variant($color, $background, $border) { ... .foreverAlone { ... } .iThink .illNeverWork& { color: $pinkUnicornRainbow; ... } }</code>
When this mixin is called within another CSS class, the generated code will not include the caller's class name. Instead, it will produce:
<code class="css">.foreverAlone { ... } .iThink .illNeverWork.callerClass { color: #123ABC; ... }</code>
To overcome this issue, you can utilize the following techniques:
Sass Versions 3.2 and Older:
<code class="sass">@mixin button-variant($color, $background, $border) { ... .foreverAlone, .iThink &.illNeverWork { color: $pinkUnicornRainbow; ... } }</code>
Sass Version 3.3:
<code class="sass">@mixin button-variant($color, $background, $border) { ... .iThink &-illNeverWork { color: $pinkUnicornRainbow; ... } }</code>
Sass Version 3.4:
<code class="sass">@mixin button-variant($color, $background, $border) { ... $parent: &; @at-root .iThink#{&} { color: $pinkUnicornRainbow; ... } }</code>
By implementing these techniques, you can effectively extend parent selectors within a mixin, ensuring that the generated code includes the caller class name.
The above is the detailed content of How to Extend Parent Selectors in SASS Mixins When Using the Ampersand (&) at the End of a Selector?. For more information, please follow other related articles on the PHP Chinese website!