Home  >  Article  >  Web Front-end  >  How to Use the Ampersand (&) in SASS Selectors: Solving Nesting Challenges with Mixins

How to Use the Ampersand (&) in SASS Selectors: Solving Nesting Challenges with Mixins

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-30 05:00:02272browse

How to Use the Ampersand (&) in SASS Selectors: Solving Nesting Challenges with Mixins

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn