我正在使用sass并发现问题.这是我想要做的一个例子:
.message-error {
background-color: red;
p& {
background-color: yellow
}
}
Run Code Online (Sandbox Code Playgroud)
预计的css:
.message-error {
background-color: red;
}
p.message-error {
background-color: yellow ;
}
Run Code Online (Sandbox Code Playgroud)
这个想法:所有带有.message-error的元素都是红色的,除非它是p.message-error.这不是现实生活中的情况,只是为了展示一个例子.
SASS无法编译这个,我甚至尝试过字符串连接.是否有一些插件可以完全相同?
注意:我知道我可以添加另一个css定义
p.message-error{....}
Run Code Online (Sandbox Code Playgroud)
在,但我想避免这种情况,并为所有.message-error定义使用一个地方.
谢谢.
cim*_*non 38
截至Sass 3.4,现在支持此功能.语法如下所示:
.message-error {
background-color: red;
@at-root p#{&} {
background-color: yellow
}
}
Run Code Online (Sandbox Code Playgroud)
请注意@at-root&符号上的指令和插值语法.如果不包含该@at-root指令将导致选择器.message-error p.message-error而不是p.message-error.
pio*_*ouM 20
Natalie Weizenbaum(Sass的首席设计师和开发人员)表示永远不会支持它:
目前,
&在语法上与元素选择器相同,因此它不能与一个元素选择器一起出现.我认为这有助于澄清它可以在哪里使用; 例如,foo&bar永远不会是一个有效的选择器(或者可能等同于foo& bar或foo &bar).我认为这个用例不足以保证改变它.
据我所知,没有可行的解决方法.
Dom*_*nic 19
您可以将当前选择器分配给一个变量,然后在任何深度使用它:
.Parent {
$p: &;
&-Child {
#{$p}:focus & {
border: 1px solid red;
}
#{$p}--disabled & {
background-color: grey;
}
}
}
Run Code Online (Sandbox Code Playgroud)
最好的办法可能就是这个(假设你的.message-error类比你的背景颜色多一点.
.message-error {
background-color: red;
}
p.message-error {
@extend .message-error;
background-color: yellow
}
Run Code Online (Sandbox Code Playgroud)
这种方法不提供紧密分组,但您可以让它们彼此靠近.
我遇到了同样的问题,所以我为此做了一个 mixin。
@mixin tag($tag) {
$ampersand: & + '';
$selectors: simple-selectors(str-replace($ampersand, ' ', ''));
$main-selector: nth($selectors, -1);
$previous-selectors: str-replace($ampersand, $main-selector, '');
@at-root {
#{$previous-selectors}#{$tag}#{$main-selector} {
@content;
}
}
}
Run Code Online (Sandbox Code Playgroud)
为了使其工作,您还需要一个字符串替换函数(来自 Hugo Giraudel):
@function str-replace($string, $search, $replace: '') {
$index: str-index($string, $search);
@if $index {
@return str-slice($string, 1, $index - 1) + $replace + str-replace(str-slice($string, $index + str-length($search)), $search, $replace);
}
@return $string;
}
Run Code Online (Sandbox Code Playgroud)
社会保障局
.foo {
color: blue;
@include tag(p) {
color: red;
}
}
Run Code Online (Sandbox Code Playgroud)
输出
.foo {
color: blue;
}
p.foo {
color: red;
}
Run Code Online (Sandbox Code Playgroud)
用例
此方法适用于嵌套选择器,但不适用于白色复合选择器。