SCSS问题:如何避免content属性中变量插值时出现多余空格
解决SCSS Mixin中Unicode转义符与变量间的空格问题
我写了一个用来生成图标伪元素内容的SCSS mixin:
@mixin icon_fn($glyph) { &::before {content: "\e#{$glyph}";} }
原本期望通过@include icon_fn("9fa")调用生成正确的Unicode转义内容,但编译后\e和变量值之间总会莫名出现空格。尝试用自定义函数移除空格也没用:
@function str-remove-whitespace($str) { @while (str-index($str, ' ') != null) { $index: str-index($str, ' '); $str: "#{str-slice($str, 0, $index - 1)}#{str-slice($str, $index + 1)}"; } @return $str; } @mixin icon_fn($glyph) { $theglyph: "\e#{$glyph}"; &::before {content: str-remove-whitespace($theglyph);} }
解决方案
问题根源是SCSS对转义字符与变量插值的解析逻辑,直接用"\e#{$glyph}"的写法会让编译器自动插入空格。换用字符串拼接+unquote函数就能解决:
@mixin icon_fn($glyph) { &::before { content: unquote('"\e' + $glyph + '"'); } }
或者也可以这么写,效果一致:
@mixin icon_fn($glyph) { &::before { content: "#{unquote('\e' + $glyph)}"; } }
原理说明
- 先通过
'"\e' + $glyph + '"'把转义前缀、变量值和引号拼接成完整字符串,比如传入"9fa"时,拼接结果是"\e9fa" - 再用
unquote()函数去掉SCSS自动给字符串加的包裹引号,确保最终编译出的CSS是content: "\e9fa";,完全没有多余空格。
内容的提问来源于stack exchange,提问作者Moseleyi
相关产品推荐
相关产品推荐

