重大变化:CSS 变量语法
旧版本的 LibSass 和 Ruby Sass 解析自定义属性声明就像任何其他属性声明一样,允许 SassScript 表达式 的完整范围作为值。但这与 CSS 不兼容。
- Dart Sass
- ✓
- LibSass
- since 3.5.0
- Ruby Sass
- since 3.5.0
CSS 规范允许在自定义属性声明中使用几乎任何字符串。尽管这些值可能对任何 CSS 属性都没有意义,但可以从 JavaScript 访问它们。当它们被解析为 SassScript 值时,有效的纯 CSS 语法无法解析。例如,聚合物库 使用它来支持纯 CSS mixin:
¥The CSS spec allows almost any string of characters to be used in a custom property declaration. Even though these values might not be meaningful for any CSS property, they could be accessed from JavaScript. When they were parsed as SassScript values, syntax that would have been valid plain CSS failed to parse. For example, the Polymer library used this to support plain-CSS mixins:
SCSS Syntax
:root {
--flex-theme: {
border: 1px solid var(--theme-dark-blue);
font-family: var(--theme-font-family);
padding: var(--theme-wide-padding);
background-color: var(--theme-light-blue);
};
}
CSS Output
:root {
--flex-theme: {
border: 1px solid var(--theme-dark-blue);
font-family: var(--theme-font-family);
padding: var(--theme-wide-padding);
background-color: var(--theme-light-blue);
};
}
为了提供与纯 CSS 的最大兼容性,最新版本的 Sass 要求在 插值法 内编写自定义属性值中的 SassScript 表达式。插值也适用于较旧的 Sass 版本,因此建议用于所有样式表。
¥To provide maximum compatibility with plain CSS, more recent versions of Sass require SassScript expressions in custom property values to be written within interpolation. Interpolation will also work for older Sass versions, and so is recommended for all stylesheets.
SCSS Syntax
$accent-color: #fbbc04;
:root {
// WRONG, will not work in recent Sass versions.
--accent-color-wrong: $accent-color;
// RIGHT, will work in all Sass versions.
--accent-color-right: #{$accent-color};
}
Sass Syntax
$accent-color: #fbbc04
:root
// WRONG, will not work in recent Sass versions.
--accent-color-wrong: $accent-color
// RIGHT, will work in all Sass versions.
--accent-color-right: #{$accent-color}
CSS Output
:root {
--accent-color-wrong: $accent-color;
--accent-color-right: #fbbc04;
}
⚠️ Heads up!
由于插值会从带引号的字符串中删除引号,因此可能需要将它们封装在 meta.inspect()
函数 中以保留它们的引号。
¥Because interpolation removes quotation marks from quoted strings, it may be
necessary to wrap them in the meta.inspect()
function to preserve their quotes.
SCSS Syntax
@use "sass:meta";
$font-family-monospace: Menlo, Consolas, "Courier New", monospace;
:root {
--font-family-monospace: #{meta.inspect($font-family-monospace)};
}
Sass Syntax
@use "sass:meta"
$font-family-monospace: Menlo, Consolas, "Courier New", monospace
:root
--font-family-monospace: #{meta.inspect($font-family-monospace)}
CSS Output
:root {
--font-family-monospace: Menlo, Consolas, "Courier New", monospace;
}