使用尾随符号 (&) 作为 class 组合选择器,而不是后代选择器

Use trailing ampersand (&) as a class combination selector, not a descendant selector

我想将 class .highlight 应用于一堆不同的元素并根据元素类型设置样式。我可以这样做:

input[type="text"].highlight {...}
select.highlight {...}
someOtherSelector.hightlight {...}

但我正在尝试使用尾随符号 (&) 使我的代码更简洁。

我试过以下方法:

.highlight {

    input[type="text"].& {
        border: 1px solid $brand-purple;
    }
}

但我收到以下错误:

Error: property "input" must be followed by a ':'

我也试过:

.highlight {

    input[type="text"]& {
        border: 1px solid $brand-purple;
    }
}

但我收到以下错误:

Invalid CSS after "[type="text"]": expected "{", was "&" "&" may only be used at the beginning of a compound selector.

是否有解决此问题的方法,或者这是否可以在 SASS 中完成?

使用 #{&} 而不是 .&。并使用 @at-root,它允许您完全打破嵌套结构,进入嵌套树的 "root"。

在SASS中这样写:

.highlight {

  @at-root input[type="text"]#{&} {
      border: 1px solid $brand-purple;
  }
}

这将在 CSS 中符合:

input[type="text"].highlight {
  border: 1px solid purple;
}

希望对您有所帮助!

你需要重新组织一下你的scss,你需要的是:

input[type="text"]  {
  &.highlight {
    border: 1px solid $brand-purple;
  }
}

*更新后编辑,您可以使用@at-root:

.highlight {
  @at-root {
    input[type="text"]  {
      &.highlight {
        border: 1px solid $brand-purple;
      }
    }
  }
}