如何复用SCSS Mixin为自定义类实现响应式字体样式?
问题分析与解决方案
核心问题
原typography Mixin写死了目标选择器(body p),导致无法作用于自定义类;添加参数时未设置默认值或调用方式错误,引发参数缺失报错。
解决方案步骤
1. 修改type.scss中的typography Mixin
调整Mixin,使其支持自定义选择器参数,并保留默认值以兼容原有用法:
// type.scss $desktop: ( p: (font-size: 16px, line-height: 1.5) ); $tablet: ( p: (font-size: 14px, line-height: 1.4) ); $mobile: ( p: (font-size: 13px, line-height: 1.3) ); @mixin font-style($props) { font-size: map-get($props, font-size); line-height: map-get($props, line-height); } // 新增可选参数$selector,默认值为原有目标选择器 @mixin typography($selector: 'body p', $element: 'p') { #{$selector} { @include font-style(map-get($desktop, $element)); @media (max-width: 768px) { @include font-style(map-get($tablet, $element)); } @media (max-width: 480px) { @include font-style(map-get($mobile, $element)); } } }
2. 在include.module.scss中正确调用Mixin
注意SCSS模块导入的命名空间规则,按需传入自定义选择器:
// include.module.scss // 导入type.scss模块,使用通配符避免命名空间前缀 @use './type' as *; // 调用Mixin,传入自定义类选择器,复用p标签的字体配置 @include typography('.searchTitle', 'p');
问题原因说明
- 直接调用原Mixin:原代码选择器固定为
body p,自定义类.searchTitle不在匹配范围内,样式不生效。 - 参数缺失报错:修改Mixin时未设置参数默认值(如写成
@mixin typography($class-name)),调用时未传参触发错误;或未正确处理SCSS模块的命名空间(如导入后未加模块前缀调用Mixin)。
内容的提问来源于stack exchange,提问作者Lazlo
相关产品推荐
相关产品推荐

