插值

插值几乎可以在 Sass 样式表的任何地方使用,用于将 SassScript 表达式 嵌入到 CSS 代码块中。 只需在以下任何位置将表达式用 #{} 包裹:

Playground

SCSS Syntax

@mixin corner-icon($name, $top-or-bottom, $left-or-right) {
  .icon-#{$name} {
    background-image: url("/icons/#{$name}.svg");
    position: absolute;
    #{$top-or-bottom}: 0;
    #{$left-or-right}: 0;
  }
}

@include corner-icon("mail", top, left);
Playground

Sass Syntax

@mixin corner-icon($name, $top-or-bottom, $left-or-right)
  .icon-#{$name}
    background-image: url("/icons/#{$name}.svg")
    position: absolute
    #{$top-or-bottom}: 0
    #{$left-or-right}: 0



@include corner-icon("mail", top, left)

CSS Output

.icon-mail {
  background-image: url("/icons/mail.svg");
  position: absolute;
  top: 0;
  left: 0;
}




在 SassScript 中在 SassScript 中 permalink

Compatibility (Modern Syntax):
Dart Sass
LibSass
Ruby Sass
since 4.0.0 (unreleased)

LibSass 和 Ruby Sass 目前使用一种较旧的语法来解析 SassScript 中的插值。对于大多数实际用途来说,它的工作方式相同, 但在运算符周围可能会表现得很奇怪。详情请参见这份文档

插值可以在 SassScript 中用于将 SassScript 注入不带引号的字符串中。这在动态生成名称(例如动画)或使用斜杠分隔的值时特别有用。请注意,SassScript 中的插值总是返回一个不带引号的字符串。

Playground

SCSS Syntax

@mixin inline-animation($duration) {
  $name: inline-#{unique-id()};

  @keyframes #{$name} {
    @content;
  }

  animation-name: $name;
  animation-duration: $duration;
  animation-iteration-count: infinite;
}

.pulse {
  @include inline-animation(2s) {
    from { background-color: yellow }
    to { background-color: red }
  }
}
Playground

Sass Syntax

@mixin inline-animation($duration)
  $name: inline-#{unique-id()}

  @keyframes #{$name}
    @content


  animation-name: $name
  animation-duration: $duration
  animation-iteration-count: infinite


.pulse
  @include inline-animation(2s)
    from
      background-color: yellow
    to
      background-color: red

CSS Output

.pulse {
  animation-name: inline-uifpe6h;
  animation-duration: 2s;
  animation-iteration-count: infinite;
}
@keyframes inline-uifpe6h {
  from {
    background-color: yellow;
  }
  to {
    background-color: red;
  }
}





💡 Fun fact:

插值对于将值注入字符串很有用,但除此之外在 SassScript 表达式中很少需要。你绝对不需要仅仅为了在属性值中使用变量而使用它。不要写 color: #{$accent},而是直接写 color: $accent

⚠️ Heads up!

在数字上使用插值几乎总是一个坏主意。插值返回不带引号的字符串,不能用于进一步的数学运算,并且会避开 Sass 内置的确保单位正确使用的保护机制。

Sass 有强大的单位算术可供使用。例如,不要写 #{$width}px,而是写 $width * 1px——或者更好的是,一开始就以 px 声明 $width 变量。这样,如果 $width 已经有单位,你将得到一个友好的错误消息,而不是编译出错误的 CSS

带引号的字符串带引号的字符串 permalink

在大多数情况下,插值会注入与表达式用作属性值时完全相同的文本。但有一个例外:带引号字符串周围的引号会被移除(即使这些带引号的字符串在列表中)。这使得可以编写包含 SassScript 中不允许的语法(如选择器)的带引号字符串,并将它们插值到样式规则中。

Playground

SCSS Syntax

.example {
  unquoted: #{"string"};
}
Playground

Sass Syntax

.example
  unquoted: #{"string"}

CSS Output

.example {
  unquoted: string;
}

⚠️ Heads up!

虽然使用这个特性将带引号的字符串转换为不带引号的字符串很诱人,但使用 string.unquote() 函数会更清晰。 不要写 #{$string},而是写 string.unquote($string)