Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
454 views
in Technique[技术] by (71.8m points)

Sass combining parent using ampersand (&) with type selectors

I am having trouble with nesting in Sass. Say I have the following HTML:

<p href="#" class="item">Text</p>
<p href="#" class="item">Text</p>
<a href="#" class="item">Link</a>

When I try to nest my styles in the following I get a compiling error:

.item {
    color: black;
    a& {
        color:blue;
   }
}

How do I reference a type selector before the parent selector when it is part of the same element?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As Kumar points out, this has been possible since Sass 3.3.0.rc.1 (Maptastic Maple).

The @at-root directive causes one or more rules to be emitted at the root of the document, rather than being nested beneath their parent selectors.

We can combine the @at-root directive along with interpolation #{} to arrive at the intended outcome.

SASS

.item {
    color: black;
    @at-root {
        a#{&} {
            color:blue;
        }
    }
}

// Can also be written like this.
.item {
    color: black;
    @at-root a#{&} {
        color:blue;
    }
}

Output CSS

.item {
    color: black;
}
a.item {
    color: blue;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...