Less - 转义
LESS - 转义
Section titled “LESS - 转义”在 LESS 中,转义允许你将任意字符串输出为 CSS 值或选择器的一部分,而不会让 LESS 尝试解释或编译它们。这对于需要使用非标准语法、专有浏览器扩展,或者字符串可能被误认为是 LESS 构造(如变量或函数调用)的情况非常有用。
转义字符串的主要方法是在其前面加上波浪号()并用引号括起来,如下所示:“string-to-escape”。
让我们用一个实际场景来演示转义,比如你需要为旧版 Internet Explorer 输出特定的滤镜语法,或者一个 LESS 可能尝试解释的 CSS 变量名。
考虑以下 HTML:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>LESS Escaping Example</title> <link rel="stylesheet" type="text/css" href="style.css"></head><body> <h1>Example using Escaping</h1> <p class="special-text">This text uses a custom property.</p> <div class="legacy-filter">This div has a legacy filter.</div></body></html>现在,让我们创建 style.less 文件:
style.less
Section titled “style.less”// 我们想用作字符串字面量以表示 CSS 自定义属性名称的变量@my-custom-prop-name: --custom-highlight-color;
.special-text { // 这里并非严格需要转义,如果 @my-custom-prop-name 以 -- 开头的话 // 但演示了如果需要将变量的值输出为属性名的一部分如何进行 // 更常见的是,对于值而言: @{my-custom-prop-name}: ~"#007bff"; // 对值使用转义字符串 color: var(@my-custom-prop-name);}
.legacy-filter { // 老式、非标准滤镜属性的示例 filter: ~"progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#000000')"; // 另一个示例:输出一个看起来像 LES 函数的字符串 content: ~"attr(data-text) '(' counter(item) ')'";}
// 在选择器中进行转义的示例(不太常见,但可行)@my-selector-suffix: "-active";.button~"@{my-selector-suffix}" { font-weight: bold;}要将 style.less 编译为 style.css,你需要使用 LESS 编译器。如果你通过 npm 全局安装了 LESS,可以运行:
lessc style.less style.css编译后,style.css 文件将包含:
style.css
Section titled “style.css”.special-text { --custom-highlight-color: #007bff; color: var(--custom-highlight-color);}
.legacy-filter { filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#cccccc', endColorstr='#000000'); content: attr(data-text) '(' counter(item) ')';}
.button-active { font-weight: bold;}转义的要点总结:
Section titled “转义的要点总结:”~”…”内部的任何内容都会直接按原样输出到 CSS 中。- 这对于 CSS hacks、专有语法或你需要阻止 LESS 解释字符串的情况至关重要。
- 如果你需要在字面字符串中包含动态值,可以在转义字符串内部使用变量插值(例如,
~”@{variable}”)。
在编译 LESS 代码后,如果你在浏览器中打开 escaping.html 文件:
- 类名为
special-text的段落将尝试使用 CSS 自定义属性—custom-highlight-color。 - 类名为
legacy-filter的 div 将应用指定的滤镜和内容规则(行为取决于浏览器对这些特定旧版或复杂内容属性的支持)。
现代替代方案,如 CSS 自定义属性(变量),减少了对某些转义技巧的需求,但转义对于特定的边缘情况仍然是一个有价值的工具。