1

有没有办法写这个css:

div.some-class{
  ...
}
span.some-class{
  ...
}

像这样使用scss?

.some-class{
  &div{
    ...
  }
  &span{
    ...
  }
}

我尝试了上述方法,但它返回错误。

4

2 回答 2

2

这取决于你想要做什么。

您显示的示例将被解释为.some-classdiv.some-classspan这将导致编译错误。本质上,与号代表父选择器。

如果div.some-classspan.some-class不共享相同的样式,您拥有的第一个块仍然是编写它的最有效方式。

如果它们共享一些相同的样式,您可以编写一个 mixin。

// Shared Styles
@mixin some-class {
  background: #f00;
  color: #fff;
}

div.some-class {
  @include some-class;
  ... other styles
}

span.some-class {
  @include some-class;
  ... other styles
}

你也可以@extend是一个现有的类:

.some-class {
  background: #f00;
  color: #fff;
}

div.some-class {
  @extend .some-class;
  ... other styles
}

span.some-class {
  @extend .some-class;
  ... other styles
}

如果您扩展现有类,该类必须是包含在文件中的根类(即它不能是嵌套类)。

也就是说,由于两个元素都有 class some-class,你可以很容易地定义常规 CSS:

.some-class {
  background: #f00;
  color: #fff;
}

div.some-class {
  ... other styles
}

span.some-class {
  ... other styles
}
于 2013-01-16T19:27:47.397 回答
2

我知道确实希望将您的代码组合成这样漂亮整洁的小块,但这是不可能的。编译代码时得到的错误非常清楚:

>>> Change detected at 14:46:18 to: test.scss
    error sass/test.scss (Line 2: Invalid CSS after "  &": expected "{", was "div{"

"div" may only be used at the beginning of a compound selector.)

当然,如果你把它反转为div&,那么你会得到这个错误:

>>> Change detected at 14:48:01 to: test.scss
    error sass/test.scss (Line 2: Invalid CSS after "  div": expected "{", was "&{"

"&" may only be used at the beginning of a compound selector.)

您唯一的选择是根本不嵌套。

.some-class {
    ...
}

div.some-class {
    ...
}

span.some-class {
    ...
}
于 2013-01-16T19:50:22.683 回答