如何结合选择器

时间:2013-01-16 18:47:13

标签: css css3 css-selectors sass

有没有办法写这个css:

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

像使用scss这样的东西?

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

我尝试了以上操作,但它返回错误。

2 个答案:

答案 0 :(得分: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
}

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

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

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

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

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

答案 1 :(得分: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 {
    ...
}