Sass 当父对象具有类时,是否更改子对象样式?

Sass 当父对象具有类时,是否更改子对象样式?,sass,Sass,我想向容器中添加一个类,它还将更改子样式 以下是我所希望的SCS: .container { .mask { background: #FFF; // When parent(.container) has ".new" class then change the ".mask" background. // possible? &&.new { background: #000; } } } 在纯css

我想向容器中添加一个类,它还将更改子样式

以下是我所希望的SCS:

.container
{
  .mask
  {
    background: #FFF;

    // When parent(.container) has ".new" class then change the ".mask" background.
    // possible?
    &&.new
    {
      background: #000;
    }
  }
}
在纯css中,可以这样做:

.container .mask{ background: #FFF; }
.container.new .mask{ background: #000; }
.container
  .mask
    background: #FFF
  &.new
    .mask
      background: #000 !important
这是我唯一能做到的方法吗

.container
{
  .mask      { background: #FFF; }
  &.new .mask{ background: #000; }
}

在sass中,您可以这样写:

.container .mask{ background: #FFF; }
.container.new .mask{ background: #000; }
.container
  .mask
    background: #FFF
  &.new
    .mask
      background: #000 !important
编辑

根据您的评论,您可以这样做:

.container
  .mask
    background: #FFF
.new
  .mask
    background: #000 !important

AFAIK Sass没有提供现成的解决方案,但这里有一个DIY解决方案

=context($context, $addition)
  @at-root #{selector-replace(&, $context, $context + $addition)}
    @content

.container
  $parent: &
  .mask
    background: #FFF
    +context($parent, '.new')
      background: #000
您需要在嵌套结构中的任何深度设置
$parent
变量,以便以后参考和修改,因为这可能会根据情况而改变


我把逻辑移到了mixin,所以它尽可能干净。它仍然有点冗长,但它没有任何不必要的重复。嗯,我希望我能在“.mask”中写,而不是在“.container”中。@YamiOdymel更新了答案真的很抱歉我的语法,我的意思是我想知道“.container”有“.new”类或不在“.mask”类中,所以也许我需要让家长的家长(?)在“.mask”中类似这样的东西,就像我的第一个代码一样,真的很抱歉。@YamiOdymel上面的SASS也应该作为背景:#000只会在容器有另一个类newalrelated时应用:这是一个很好的答案。用这个。我不知道为什么会被否决。顺便说一下,如果有更好的解决方案,那么我想看看。