Sass:使用 & 符号“&”作为具有特定类的正文标签

Mor*_*mdy 2 css sass

演示:https : //codepen.io/moradxd/pen/WJpPyQ

假设我有这个 HTML 代码:

<body class="boxed">
  <div class="text-white">
    <a href="#" class="btn-featured">Button</a>
  </div>
</dody>
Run Code Online (Sandbox Code Playgroud)

我正在使用这个 sass 代码如下:

.boxed {
  // error with using "Ampersand"
  body& {

  }
}
Run Code Online (Sandbox Code Playgroud)

但这会导致编译错误,其中说:

在此处输入图片说明

虽然我想要的结果如下:

// This the result i want
body.boxed {

}
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样使用它,它会产生我正在寻找的结果:

// I know i can use this
body {
  &.boxed {

  }
}
Run Code Online (Sandbox Code Playgroud)

但是为了组织目的,我想将 .boxed 类代码与正文 css 代码内部分开。

那么为什么不允许这样做,尽管元素及其父级的类似代码适用于以下情况:

// Although this similar code for element and 
// it's parent is working
.btn-featured {
  .text-white & {
    font-size: 30px;
  }
}
Run Code Online (Sandbox Code Playgroud)

事实上,我希望知道为什么不允许这样做!

pat*_*pan 5

你好莫拉德你需要使用 @at-root

.boxed {
  @at-root body#{&} {
     color: red;
  }
}
Run Code Online (Sandbox Code Playgroud)

代码笔

  • 如果您尝试在 &amp; 和 body 之间留出空间,那么它将起作用。但是每当你想连接两个选择器或字符串时,你需要使用插值 (2认同)