【问题标题】:How to conjoin selectors如何连接选择器
【发布时间】:2012-12-31 04:33:42
【问题描述】:

有没有办法写这个css:

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

像这样使用 scss?

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

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

【问题讨论】:

  • 不起作用的原因是因为type selectors always come first。你没有提到它是什么类型的错误,所以我不知道它是编译成无效的 CSS 还是在编译时抛出错误。无论哪种方式,它都是无效的。
  • @BoltClock 错误来自 scss。我正在寻找一种在 scss 中表达这一点的方法。只要我描述的scss输出,css就没有问题。 & 无论如何都不是 css;它的 scss。
  • 即使&div 按您预期的方式工作,它也会生成无效的 CSS,因为顺序不正确。
  • @cimmanon 我不认为这是重复的
  • @YehudaKatz 如果 OP 按照生成有效 CSS 的顺序放置了 &,这将是完全重复的。

标签: css css-selectors sass


【解决方案1】:

这取决于你想做什么。

您显示的示例将被解释为.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
}

【讨论】:

  • 想要解释为什么这被否决了吗?如果这里有不正确的信息,我很乐意更正。
【解决方案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 {
    ...
}

【讨论】:

  • 谢谢。你给了我答案:不可能。
猜你喜欢
  • 2021-01-24
  • 2015-04-16
  • 1970-01-01
  • 2019-06-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-19
  • 1970-01-01
相关资源
最近更新 更多