Home > Web Front-end > CSS Tutorial > How Can I Use Ampersand (&) Effectively in SASS Selectors?

How Can I Use Ampersand (&) Effectively in SASS Selectors?

Barbara Streisand
Release: 2024-10-29 04:49:29
Original
698 people have browsed it

How Can I Use Ampersand (&) Effectively in SASS Selectors?

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&amp; {

            color: $pinkUnicornRainbow;
            ...
        }
  }</code>
Copy after login

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>
Copy after login

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 {
    &amp;, &amp;.bar, &amp;#bar, &amp;:after, &amp;[active] {
        color: red;
    }
}

.foo {
    .bar &amp; {
        color: red;
    }
}</code>
Copy after login

From Sass 3.3 onwards, the syntax is simplified, allowing for usage such as:

<code class="sass">.foo {
    &amp;bar, &amp;-bar {
        color: red;
    }
}</code>
Copy after login

For Sass 3.4 and later, an even more powerful approach is available:

<code class="sass">.foo {
    $foo: &amp;;
    @at-root bar#{&amp;} {
        color: red;
    }
}</code>
Copy after login

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!

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