我正在为我当前的项目使用Sass (.scss)。

下面的例子:

HTML

<div class="container desc">
    <div class="hello">
        Hello World
    </div>
</div>

SCSS

.container {
    background:red;
    color:white;

    .hello {
        padding-left:50px;
    }
}

这很有效。

我可以处理多个类同时使用嵌套样式。

在上面的例子中,我说的是:

CSS

.container.desc {
    background:blue;
}

在这种情况下,所有div.container通常是红色的,但div.container.desc将是蓝色的。

我如何能巢这个内部容器与Sass?


当前回答

这对我很有效

<div class="container">
  <div class="desc">
    desc
  </div>
  <div class="asc">
    asc
  </div>
</div>

.container{
  &.desc {
    background: blue;
  }
  &.asc {
    background: red;
  }
}

其他回答

使用&

SCSS

.container {
    background:red;
    color:white;

    &.hello {
        padding-left:50px;
    }
}

https://sass-lang.com/documentation/style-rules/parent-selector

如果是这种情况,我认为您需要使用更好的方法来创建类名或类名约定。例如,如您所说,您希望.container类根据特定的用法或外观具有不同的颜色。你可以这样做:

SCSS

.container {
  background: red;

  &--desc {
    background: blue;
  }

  // or you can do a more specific name
  &--blue {
    background: blue;
  }

  &--red {
    background: red;
  }
}

CSS

.container {
  background: red;
}

.container--desc {
  background: blue;
}

.container--blue {
  background: blue;
}

.container--red {
  background: red;
}

上面的代码基于类命名约定中的BEM方法。你可以检查这个链接:BEM -块元素修饰器方法学

除了Cristoph的回答,如果您想在声明中更具体,您可以引用容器类组件的所有子组件。这可以用:

.container {
// ...
  #{&}.hello {
     padding-left: 50px;
  }
}

编译为:

.container .container.hello {
   padding-left: 50px;
}

希望这对你有帮助!

这对我很有效

<div class="container">
  <div class="desc">
    desc
  </div>
  <div class="asc">
    asc
  </div>
</div>

.container{
  &.desc {
    background: blue;
  }
  &.asc {
    background: red;
  }
}

Christoph的回答很完美。然而,有时你可能想上更多的课。在这种情况下,您可以尝试@at-root和#{}css特性,它们可以使用&使两个根类相邻。

这是行不通的(因为之前没有&规则):

container {
    background:red;
    color:white;
    
    .desc& {
      background: blue;
    }

    .hello {
        padding-left:50px;
    }
}

但这将(使用@at-root + #{&}):

container {
    background:red;
    color:white;
    
    @at-root .desc#{&} {
      background: blue;
    }

    .hello {
        padding-left:50px;
    }
}