Home  >  Article  >  Web Front-end  >  How does the ampersand (&) work in SASS selectors to dynamically generate child selectors?

How does the ampersand (&) work in SASS selectors to dynamically generate child selectors?

Susan Sarandon
Susan SarandonOriginal
2024-10-28 20:04:31471browse

How does the ampersand (&) work in SASS selectors to dynamically generate child selectors?

Ampersand (&) in SASS Selectors

In SASS, the ampersand (&) has a special significance when used within selectors. As demonstrated in the example mixin provided, it can be employed to append part of the parent selector to a child selector.

For Sass versions up to 3.2, the following syntax is acceptable:

.foo {
    &, &.bar, &#bar, &:after, &[active] {
        color: red;
    }
}

Additionally, this syntax is supported:

.foo {
    .bar & {
        color: red;
    }
}

From Sass 3.3 onwards, the following syntax is valid:

.foo {
    &bar, &-bar {
        color: red;
    }
}

Finally, Sass 3.4 introduces an alternative approach:

.foo {
    $foo: &;
    @at-root bar#{&} {
        color: red;
    }
}

By utilizing these techniques, you can dynamically generate child selectors that include parts of the parent selector. This is particularly useful when creating mixins that can be applied to different parent classes.

The above is the detailed content of How does the ampersand (&) work in SASS selectors to dynamically generate child selectors?. 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