Sass .scss:嵌套和多个类?
我为我当前的项目使用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通常是red但div.container.desc将是蓝色的。 
 我怎样才能将这个内部container与Sass嵌套? 
 您可以使用父select器引用 & ,它将在编译之后由父select器replace: 
举个例子:
 .container { background:red; &.desc{ background:blue; } } /* compiles to: */ .container { background: red; } .container.desc { background: blue; } 
  &会完全解决,所以如果你的父母select器是嵌套的,嵌套将在更换&之前解决。 
这种表示法最常用于编写伪元素和-class :
 .element{ &:hover{ ... } &:nth-child(1){ ... } } 
 但是,您可以将&放置在您喜欢的任何位置* ,因此也可以这样做: 
 .container { background:red; #id &{ background:blue; } } /* compiles to: */ .container { background: red; } #id .container { background: blue; } 
但是请注意,这会以某种方式破坏您的嵌套结构,因此可能会增加在样式表中查找特定规则的工作量。
  *:在&前面不允许有空格之外的其他字符。 所以你不能直接连接selector + & – #id&会抛出一个错误。 
 如果是这样的话,我认为你需要使用更好的方式来创build类名或类名称约定。 例如,就像你所说的,你希望.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 – 块元素修饰符方法