插值(Interpolation)

插值幾乎可以用在 Sass 樣式表的任何地方,以將 SassScript 運算式的結果嵌入到 CSS 區塊中。只需將運算式用 #{} 包起來,即可在以下任何位置使用:

程式碼試驗場

SCSS 語法

@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);
程式碼試驗場

Sass 語法

@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 輸出

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




在 SassScript 中在 SassScript 中的永久連結

相容性(現代語法)
Dart Sass
LibSass
Ruby Sass
自 4.0.0 版起(尚未發佈)

LibSass 和 Ruby Sass 目前使用較舊的語法來解析 SassScript 中的插值。在大多數實際應用中,它的工作原理相同,但在處理運算子時可能會出現異常行為。詳情請參閱此文件

在 SassScript 中,可以使用插值(Interpolation)將 SassScript 注入到無引號字串中。這在動態生成名稱(例如動畫名稱)或使用斜線分隔值時特別有用。請注意,SassScript 中的插值始終返回無引號字串。

程式碼試驗場

SCSS 語法

@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 }
  }
}
程式碼試驗場

Sass 語法

@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 輸出

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





💡 小知識

插值對於將值注入字串非常有用,但在 SassScript 表達式中,除了這種情況外,很少需要使用它。您絕對不需要使用它來在屬性值中使用變數。您可以直接寫 `color: $accent`,而不是寫 `color: #{$accent}`!

⚠️ 注意!

將插值與數字一起使用幾乎總是一個壞主意。插值返回的無引號字串不能用於任何進一步的數學運算,並且它避開了 Sass 的內置安全措施,以確保正確使用單位。

Sass 具有強大的單位運算功能,您可以改用它。例如,不要寫 `#{$width}px`,而是寫 `$width * 1px`——或者更好的是,一開始就用 `px` 聲明 `$width` 變數。這樣,如果 `$width` 已經有單位,您會收到一個友善的錯誤訊息,而不是編譯出錯誤的 CSS。

引號字串引號字串永久連結

在大多數情況下,插值注入的文字與將表達式用作屬性值時使用的文字完全相同。但有一個例外:引號字串周圍的引號會被移除(即使這些引號字串在列表中也是如此)。這使得編寫包含 SassScript 中不允許的語法(例如選擇器)的引號字串並將它們插入樣式規則成為可能。

程式碼試驗場

SCSS 語法

.example {
  unquoted: #{"string"};
}
程式碼試驗場

Sass 語法

.example
  unquoted: #{"string"}

CSS 輸出

.example {
  unquoted: string;
}

⚠️ 注意!

雖然很想使用此功能將引號字串轉換為無引號字串,但使用`string.unquote()` 函式會更清晰。不要寫 `#{$string}`,而是寫 `string.unquote($string)`!