Home > Web Front-end > CSS Tutorial > 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
Release: 2024-10-30 05:00:02
Original
404 people have browsed it

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;
    ...
}
Copy after login

Solutions

For Sass versions 3.2 and below, valid ways to use the parent selector include:

&, &.bar, &#bar, &:after, &[active]
Copy after login

In Sass 3.3, the following syntax is added:

&bar, &-bar
Copy after login

Sass 3.4 introduces a new feature where the ampersand can be assigned to a variable and used within an @at-root rule:

$foo: &;
Copy after login
@at-root bar#{&} {
    color: red;
}
Copy after login

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;
        ...
    }
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template