问题
I want to do something like this:
@mixin context($size) {
body.#{$size} {
@content
}
}
div {
span {
font-size: 2em;
@include context('large') {
& {
font-size: 5em;
}
}
}
}
To produce:
div span {
font-size: 2em;
}
body.large div span {
font-size: 5em;
}
What it ACTUALLY (predictably) produces:
div span {
font-size: 2em;
}
div span body.large {
font-size: 5em;
}
I could just replicate the selectors inside different mixins, but given that selectors could be complex that's a lot of extra junk:
@include context('large') {
div {
span {
font-size: 5em;
}
}
}
I could make the selectors into mixins so I don't have to repeat them each time, but...
Isn't there a way to use placeholders, maybe in combination with mixins, to get what I want in the first two code blocks above?
回答1:
You just need to move the &
to be part of the mixin:
@mixin context($size) {
body.#{$size} & {
@content
}
}
div {
span {
font-size: 2em;
@include context('large') {
font-size: 5em;
}
}
}
Output:
div span {
font-size: 2em;
}
body.large div span {
font-size: 5em;
}
As of Sass 3.4, you can write this to work both inside a selector and at the root of the document:
@mixin optional-at-root-nest($sel) {
@at-root #{if(not &, $sel, selector-nest($sel, &))} {
@content;
}
}
@mixin context($size) {
@include optional-at-root-nest('body.#{$size}') {
@content
}
}
div {
span {
font-size: 2em;
@include context('large') {
font-size: 5em;
}
}
}
@include context('large') {
font-size: 2em;
}
来源:https://stackoverflow.com/questions/19031079/sass-content-block-mixin-or-placeholder-that-takes-contextual-selectors-and-a