如何用 Sass 生成 `.sr-only` 工具类?
解读
在国内前端面试中,手写“无障碍隐藏”工具类是高频考点。面试官不仅考察你是否知道 .sr-only 的最终CSS规则,更关注你能否用 Sass 的变量、Mixin、条件控制等机制把“写死的三行样式”抽象成可配置、可复用、可扩展的工程方案。回答时务必体现“设计令牌化、逻辑参数化、编译产物最优化”这三点,才能拿到高分。
知识点
- 无障碍隐藏四大核心属性:
position:absolute、width:1px、height:1px、overflow:hidden,缺一不可。 - Sass 变量:用
$声明,支持!default实现“可覆盖默认值”。 - Mixin 与参数默认值:
@mixin sr-only($focusable: false),通过布尔参数区分“纯隐藏”与“聚焦时可见”两种场景。 - @content 与 @if:利用
@content让调用者追加自定义样式;用@if在编译期做条件分支,零运行时成本。 - @at-root:把编译后的类名提升到顶层,避免嵌套选择器带来的权重污染。
- BEM 与命名空间:国内大厂普遍要求工具类加
u-或util-前缀,防止和业务类冲突。 - 编译后体积:通过 Sass 的
--style=compressed与/*! purgecss start ignore */注释,配合构建工具做摇树优化,防止被误删。
答案
// 设计令牌:可全局覆盖
$sass-sr-only-width: 1px !default;
$sass-sr-only-height: 1px !default;
$sass-sr-only-padding: 0 !default;
$sass-sr-only-border: 0 !default;
$sass-sr-only-namespace: 'u' !default;
// 核心 Mixin:支持两种模式
@mixin sr-only($focusable: false) {
position: absolute !important;
width: $sass-sr-only-width !important;
height: $sass-sr-only-height !important;
padding: $sass-sr-only-padding !important;
margin: -1px !important;
overflow: hidden !important;
clip: rect(0 0 0 0) !important;
white-space: nowrap !important;
border: $sass-sr-only-border !important;
@if $focusable {
&:active,
&:focus {
position: static !important;
width: auto !important;
height: auto !important;
margin: 0 !important;
overflow: visible !important;
clip: auto !important;
white-space: normal !important;
}
}
}
// 使用 @at-root 生成顶层工具类
@at-root {
.#{$sass-sr-only-namespace}-sr-only {
@include sr-only;
}
.#{$sass-sr-only-namespace}-sr-only--focusable {
@include sr-only($focusable: true);
}
}
编译后(compressed):
.u-sr-only{position:absolute!important;width:1px!important;height:1px!important;padding:0!important;margin:-1px!important;overflow:hidden!important;clip:rect(0 0 0 0)!important;white-space:nowrap!important;border:0!important}
.u-sr-only--focusable:active,.u-sr-only--focusable:focus{position:static!important;width:auto!important;height:auto!important;margin:0!important;overflow:visible!important;clip:auto!important;white-space:normal!important}
拓展思考
- RTL 场景:若项目需兼容阿拉伯语,可在 Mixin 里增加
$rtl参数,利用 Sass 的@if输出left:-10000px或right:-10000px,避免硬编码方向。 - 暗色模式:虽然
.sr-only本身不可见,但若内部包含 SVG 图标,需把fill设为currentColor,防止高对比度模式下出现幽灵像素。 - 微前端隔离:在 qiankun 等沙箱环境里,给工具类再加
[data-qiankun]属性限定,防止样式泄露到基座应用。 - 自动化测试:用 jest-scss-parser 做单元快照,确保升级 Sass 版本后编译产物 diff 为零,回归成本为零。