Bootstrap中DartSass变量的正确用法及字体前置配置问题
将自定义字体前置到Bootstrap字体列表的正确实现
我需要把自定义偏好字体放到Bootstrap的字体列表最前面,之前用下面的代码实现,但现在失效了,问题出在多单词字体名称无法正确转义——尤其是赋值给CSS变量时,引号总是丢失。查文档知道用meta.inspect()能保留引号,但Bootstrap本身没这么写,求符合Bootstrap风格的正确实现方式。
之前的实现代码
$_tmp_list: $font-family-sans-serif; $font-family-sans-serif: "Nunito"; $headings-font-family: "Exo 2"; @each $_tmp_elem in $_tmp_list { $font-family-sans-serif: list.append($font-family-sans-serif, $_tmp_elem, $separator: comma); $headings-font-family: list.append($headings-font-family, $_tmp_elem, $separator: comma); } $btn-font-family: $headings-font-family;
测试不同写法的编译结果
我测试了多种字体变量定义方式,代码如下:
$extra-font-noesc: Exo 2, Helvetica Neue; $extra-font-esc: 'Exo 2', 'Helvetica Neue'; $extra-font-bresc: ['Exo 2', 'Helvetica Neue']; $extra-font-presc: ('Exo 2', 'Helvetica Neue'); .crap { font-family: $extra-font-noesc; font-family: $extra-font-esc; font-family: $extra-font-bresc; font-family: $extra-font-presc; --my-font-family: #{$extra-font-noesc}; --my-font2-family: #{$extra-font-esc}; --my-font3-family: #{$extra-font-bresc}; --my-font4-family: #{$extra-font-presc}; }
编译后发现,直接给font-family属性赋值时带引号的写法能正常保留引号,但赋值给CSS变量时,所有写法的引号都会丢失:
.crap { font-family: Exo 2, Helvetica Neue; font-family: "Exo 2", "Helvetica Neue"; font-family: ["Exo 2", "Helvetica Neue"]; font-family: "Exo 2", "Helvetica Neue"; --my-font-family: Exo 2, Helvetica Neue; --my-font2-family: Exo 2, Helvetica Neue; --my-font3-family: [Exo 2, Helvetica Neue]; --my-font4-family: Exo 2, Helvetica Neue; }
正确实现方式
方式1:用Sass列表前置方法(推荐,符合Bootstrap变量风格)
Bootstrap的字体变量本身是逗号分隔的Sass列表,直接用list.prepend()把自定义字体加到原列表头部,无需循环,同时处理CSS变量时手动保留引号:
// 保存Bootstrap原始字体列表 $_original-sans-serif: $font-family-sans-serif; $_original-headings: $headings-font-family; // 前置自定义字体到对应列表 $font-family-sans-serif: list.prepend($_original-sans-serif, "Nunito", $separator: comma); $headings-font-family: list.prepend($_original-headings, "Exo 2", $separator: comma); // 按钮字体继承标题字体 $btn-font-family: $headings-font-family; // 赋值给CSS变量时,用list.join拼接成带引号的字符串 :root { --font-family-sans-serif: "#{list.join($font-family-sans-serif, ', ')}"; --headings-font-family: "#{list.join($headings-font-family, ', ')}"; }
方式2:直接字符串拼接
如果不需要保留列表结构,也可以直接用字符串拼接的方式覆盖变量,这样赋值给CSS变量时引号也能保留:
// 定义自定义字体(带引号) $custom-sans-serif: "Nunito"; $custom-headings: "Exo 2"; // 直接拼接覆盖Bootstrap变量 $font-family-sans-serif: #{$custom-sans-serif}, #{$font-family-sans-serif}; $headings-font-family: #{$custom-headings}, #{$headings-font-family}; $btn-font-family: $headings-font-family; // 直接赋值CSS变量即可 :root { --font-family-sans-serif: #{$font-family-sans-serif}; --headings-font-family: #{$headings-font-family}; }
这两种方式都不需要用到meta.inspect(),完全符合Bootstrap的变量覆盖逻辑,同时解决了CSS变量赋值时的引号丢失问题。
内容的提问来源于stack exchange,提问作者PMc
相关产品推荐
相关产品推荐

