使用 & 在 class 中嵌入伪元素

Embed pseudo element in class with &

我正在用 CSS/JS 构建一个旋钮,我在一个示例中偶然发现了 CSS 语法,我想在我的代码中重现它,但它似乎不起作用。我也尝试强制不同 z-index 但没有成功。

这是有效的:

.knob 
{
  position: relative;
  width: 100px; height: 100px;
  border-radius: 50%;
  background: gray;
  transform: rotate(0deg);
}

.knob:before
{
  content: '';
  position: absolute;
  width: 12px; height: 12px;
  left: 44px; top: 12px;
  border-radius: 50%;
  background: white;
}

这就是我想要做的:

.knob 
{
  position: relative;
  width: 100px; height: 100px;
  border-radius: 50%;
  background: gray;
  transform: rotate(0deg);

  &:before
  {
    content: '';
    position: absolute;
    width: 12px; height: 12px;
    left: 44px; top: 12px;
    border-radius: 50%;
    background: white;
  }
}

我相信它应该有相同的结果,但作为一个诚实的 CSS 新手,我不明白这是怎么回事。 Here's a CodePen with the full code.

那个语法是SCSS语法。您不能在 css 文件中编写这样的代码。您可以设置从 SCSSCSS 的编译,然后将您的代码写入 S CSS 文件。