Ampersand (&) in SASS Selectors: Mastering Its End and In-Line Uses
The ampersand character (&) plays a crucial role in SASS selectors, allowing you to reference the parent selector effectively. However, its usage can be tricky, especially when it appears at the end or as part of a selector.
Problem:
Consider the following mixin in SASS:
<code class="sass">@mixin button-variant($color, $background, $border) { ... .foreverAlone{ ... } .iThink .illNeverWork& { color: $pinkUnicornRainbow; ... } }</code>
When called within various div classes, this mixin fails to generate the intended CSS. Instead of producing something like this:
<code class="css">.callerClass .foreverAlone{ ... } .callerClass .iThink .illNeverWork.callerClass{ color: #123ABC; ... }</code>
it produces incorrect output.
Solution:
To achieve the desired CSS, understanding the nuances of ampersand usage is essential. In SASS versions 3.2 and older, the following valid ways can be used to refer to the parent selector:
<code class="sass">.foo { &, &.bar, &#bar, &:after, &[active] { color: red; } } .foo { .bar & { color: red; } }</code>
From Sass 3.3 onwards, the syntax is simplified, allowing for usage such as:
<code class="sass">.foo { &bar, &-bar { color: red; } }</code>
For Sass 3.4 and later, an even more powerful approach is available:
<code class="sass">.foo { $foo: &; @at-root bar#{&} { color: red; } }</code>
Utilizing these techniques, you can effectively handle ampersand usage in SASS selectors, enabling you to generate precise and maintainable CSS outputs.
The above is the detailed content of How Can I Use Ampersand (&) Effectively in SASS Selectors?. For more information, please follow other related articles on the PHP Chinese website!