SASS:内容块混合(或占位符),它接受上下文选择器,并将它们附加到mixin中的选择器 [英] SASS: content block mixin (or placeholder) that takes contextual selectors and appends them to selector in mixin
问题描述
我想这样做:
@mixin context($size) {
body.#{$size} {
@content
}
}
div {
span {
font-size: 2em;
@include context('large') {
& {
font-size: 5em;
}
}
}
}
产生:
div span {
font-size: 2em;
}
body.large div span {
font-size: 5em;
}
ACTUALLY(可预测)产生的结果:
What it ACTUALLY (predictably) produces:
div span {
font-size: 2em;
}
div span body.large {
font-size: 5em;
}
我可以复制不同mixins里面的选择器,复杂,这是很多额外的垃圾:
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;
}
}
}
mixins,所以我不必每次都重复,但...
I could make the selectors into mixins so I don't have to repeat them each time, but...
没有办法使用占位符,也许与mixins组合,得到上面的前两个代码块中我想要什么?
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?
推荐答案
你只需要移动
作为mixin的一部分:
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;
}
}
}
输出:
div span {
font-size: 2em;
}
body.large div span {
font-size: 5em;
}
从Sass 3.4开始,您可以将其写入选择器
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;
}
这篇关于SASS:内容块混合(或占位符),它接受上下文选择器,并将它们附加到mixin中的选择器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!