如何在SCSS中避免扩展类/混入混合宏时生成重复CSS属性?
问题描述
我有两个可通过@extend(或@include引入的混合宏)使用的SCSS类:
.small-text { font-family: "MyFontFamily"; color: black; line-height: 1rem; font-size: 1rem; } .large-text { font-family: "MyFontFamily"; color: black; line-height: 1.4rem; font-size: 1.4rem; }
平时直接@extend使用没问题:
h1 { @extend .large-text; } h3 { @extend .small-text; }
但需要通过类名或媒体查询切换文本大小时,比如这么写:
h3 { @extend .small-text; &.big { @extend .large-text; } }
编译后的CSS会出现大量重复属性:
h3 { font-family: "MyFontFamily"; color: black; line-height: 1rem; font-size: 1rem; } h3.big { font-family: "MyFontFamily"; color: black; line-height: 1.4rem; font-size: 1.4rem; }
想知道有没有办法让第二个选择器只包含和第一个相比变化的属性?
解决方案
方法1:拆分公共样式与可变样式
把两个类的公共属性抽成单独的占位符(避免编译成无用的全局类),可变属性单独定义:
// 公共基础样式用占位符,不会被编译成独立CSS类 %base-text { font-family: "MyFontFamily"; color: black; } .small-text { @extend %base-text; line-height: 1rem; font-size: 1rem; } .large-text { @extend %base-text; line-height: 1.4rem; font-size: 1.4rem; }
使用时直接继承基础样式和对应尺寸样式:
h3 { @extend %base-text; @extend .small-text; &.big { @extend .large-text; } }
编译后会自动合并公共属性,只输出变化部分:
h3 { font-family: "MyFontFamily"; color: black; line-height: 1rem; font-size: 1rem; } h3.big { line-height: 1.4rem; font-size: 1.4rem; }
方法2:用带参数的混合宏封装
直接用mixin把文本样式封装起来,通过参数控制可变属性,切换时只传差异值:
@mixin text-style($size: 1rem, $line-height: $size) { font-family: "MyFontFamily"; color: black; font-size: $size; line-height: $line-height; } // 预设小号、大号样式(可选,方便全局调用) .small-text { @include text-style(); } .large-text { @include text-style(1.4rem); }
使用时:
h3 { @include text-style(); &.big { @include text-style(1.4rem); } }
编译后同样只输出变化的属性:
h3 { font-family: "MyFontFamily"; color: black; font-size: 1rem; line-height: 1rem; } h3.big { font-size: 1.4rem; line-height: 1.4rem; }
方法3:结合CSS变量实现
如果项目支持CSS变量,可以把可变属性定义为变量,切换时只覆盖变量值,代码最简洁:
%base-text { font-family: "MyFontFamily"; color: black; font-size: var(--text-size); line-height: var(--text-line-height); } .small-text { @extend %base-text; --text-size: 1rem; --text-line-height: 1rem; } .large-text { @extend %base-text; --text-size: 1.4rem; --text-line-height: 1.4rem; }
使用时:
h3 { @extend %base-text; --text-size: 1rem; --text-line-height: 1rem; &.big { --text-size: 1.4rem; --text-line-height: 1.4rem; } }
编译后的CSS:
h3 { font-family: "MyFontFamily"; color: black; font-size: var(--text-size); line-height: var(--text-line-height); --text-size: 1rem; --text-line-height: 1rem; } h3.big { --text-size: 1.4rem; --text-line-height: 1.4rem; }
内容的提问来源于stack exchange,提问作者Tyler V.
相关产品推荐
相关产品推荐

