Sass - 如果 class 有这个父级

Sass - if class has this parent

有没有办法让 Sass 的嵌套元素没有明确的 class 名称?

采取这样的方式:

.foo {color: blue;}
p.foo {background: yellow;}
span.foo {background: red;}

<p class="foo">Styled paragraph text</p>
<span class="foo">Styled span text</span>

然后把它变成类似这样的东西:

.foo {
  color: blue;  

  & p {
    background: yellow;
  }

  & span {
    background: red;
  }

}

fiddle

根据 this GitHub issue,从 SASS v3.3.0 开始,您可以使用以下内容:

.foo {
  color: blue;  
  @at-root {
    p#{&} {
      background: yellow;
    }
    span#{&} {
      background: red;
    }
  }
}

输出:

.foo {
  color: blue;
}
p.foo {
  background: yellow;
}
span.foo {
  background: red;
}