CSS 我可以为选择器使用变量吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12743837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:24:11  来源:igfitidea点击:

Can I use variables for selectors?

cssvariablessasscss-selectors

提问by Johansrk

I have this variable:

我有这个变量:

$gutter: 10;

I want to use it in a selector like so SCSS:

我想在像 SCSS 这样的选择器中使用它:

.grid+$gutter {
    background: red;
}

so the output becomes CSS:

所以输出变成了 CSS:

.grid10 {
    background: red;
}

But this doesn't work. Is it possible?

但这不起作用。是否可以?

回答by glortho

$gutter: 10;

.grid#{$gutter} {
    background: red;
}

If used in a string for example in a url:

如果在字符串中使用,例如在 url 中:

background: url('/ui/all/fonts/#{$filename}.woff')

回答by fk_

From the Sass Reference on "Interpolation":

来自关于“插值”Sass 参考

You can also use SassScript variables in selectors and property names using #{} interpolation syntax:

您还可以使用 #{} 插值语法在选择器和属性名称中使用 SassScript 变量:

$gutter: 10;

.grid#{$gutter} {
    background: red;
}

Furthermore, the @eachdirective is not needed to make interpolation work, and as your $gutteronly contains one value, there's no need for a loop.

此外,@each不需要该指令来使插值工作,并且由于您$gutter只包含一个值,因此不需要循环。

If you had multiple values to create rules for, you could then use a Sass listand @each:

如果您有多个值要为其创建规则,则可以使用Sass 列表@each

$grid: 10, 40, 120, 240;

@each $i in $grid {
  .g#{$i}{
    width: #{$i}px;
  }
}

...to generate the following output:

...生成以下输出:

.g10  { width: 10px; }
.g40  { width: 40px; }
.g120 { width: 120px; }
.g240 { width: 240px; }

Here are some more examples..

这里还有一些例子。.

回答by Johansrk

Here is the solution

这是解决方案

$gutter: 10;

@each $i in $gutter {
  .g#{$i}{
     background: red;
  }
}

回答by Artemee Senin

if it would be a vendor prefix, in my case the mixin did not compile. So I used this example

如果它是供应商前缀,在我的情况下,mixin 没有编译。所以我用了这个例子

@mixin range-thumb()
  -webkit-appearance: none;
  border: 1px solid #000000;
  height: 36px;
  width: 16px;
  border-radius: 3px;
  background: #ffffff;
  cursor: pointer;
  margin-top: -14px; 
  box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d;

input[type=range]
  &::-webkit-slider-thumb
    @include range-thumb()
  &::-moz-range-thumb
    @include range-thumb()
  &::-ms-thumb
    @include range-thumb()