如何强制所有可交互元素在聚焦时有非零 outline-offset?
解读
面试官抛出这道题,核心想验证三件事:
- 你是否知道“可交互元素”在 CSS 语义里到底指哪些(link、button、input、select、textarea、summary、contenteditable 元素、tabindex≥0 的元素等)。
- 你是否理解 outline-offset 为零或负值时,在高对比模式、Windows 高亮主题、深色模式或品牌色接近背景的场景下,焦点框会“贴边”甚至“内陷”,导致可访问性事故。
- 你是否能把“强制”落地到工程化流程:写一条 Stylelint 规则,让 CI 直接卡死不合规的代码,而不是口头提醒。
国内大厂(阿里、腾讯、字节、美团)在 2023 年后全部把“焦点可见”写进内部《前端代码红线》,一旦扫描到 outline:0 或 outline-offset:0 就直接打回,因此这道题是“红线”级考点。
知识点
- outline-offset 语法与取值
outline-offset: <length> | inherit | initial | unset;其中 <length> 接受 px、em、rem、vmin 等,负值会使轮廓向内收缩。 - 可交互元素选择器全集(需覆盖伪类)
:is(a, button, input, select, textarea, summary, [contenteditable], [tabindex]:not([tabindex="-1"])):focus - Stylelint 自定义规则三种写法
a) 插件 plugin:新建 rules/outline-offset-enforce.js,注册 stylelint.createPlugin。
b) 行内 stylelint-rule 包:发布到私有 npm,供全域统一。
c) 基于内置规则 selector-disallowed-list 做“反向黑名单”——禁止出现 outline-offset:0 的声明块。 - PostCSS AST 节点类型
Declaration(属性名、属性值)、Rule(选择器)、AtRule(媒体查询等)。遍历 Declaration 时,需同时检测选择器是否命中“可交互”白名单。 - 自动修复
在插件里提供 fix 函数,把 outline-offset:0 直接替换成 outline-offset:2px(或设计系统变量 --focus-offset)。 - 国内合规参考
GB/T 37668-2019《信息技术 互联网内容无障碍可访问性技术要求》4.2.3 焦点可见条款;工信部 2021 年 App 专项整治公告。
答案
落地步骤(可直接写进简历“工程化亮点”):
-
在公司私有 npm 创建包 @corp/stylelint-plugin-a11y
目录结构
lib/rules/enforce-focus-outline-offset.js
index.js 统一导出 -
插件核心代码(CommonJS,兼容 Stylelint 14+)
const stylelint = require('stylelint');
const { report, ruleMessages, validateOptions } = stylelint.utils;
const ruleName = 'corp/a11y-enforce-focus-outline-offset';
const messages = ruleMessages(ruleName, {
expected: (selector) => `可交互元素 "${selector}" 在 :focus 时必须设置非零 outline-offset`,
});
const interactiveSelector = ':is(a, button, input, select, textarea, summary, [contenteditable], [tabindex]:not([tabindex="-1"]))';
module.exports = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOption = {}, context) {
return (root, result) => {
validateOptions(result, ruleName, {
actual: primaryOption,
possible: [true],
});
root.walkRules(rule => {
// 只检查包含 :focus 的规则
if (!rule.selector.includes(':focus')) return;
// 判断选择器是否匹配可交互元素
const isInteractive = rule.selector.split(',').some(s => {
try {
return require('postcss-selector-parser')(selectors => {
return selectors.walkTags/tag => {
if (tag.value === 'a' || tag.value === 'button') return true;
};
}).processSync(s);
} catch { return false; }
});
if (!isInteractive) return;
let hasNonZeroOffset = false;
rule.walkDecls('outline-offset', decl => {
if (decl.value && decl.value !== '0' && decl.value !== '0px') {
hasNonZeroOffset = true;
}
});
if (!hasNonZeroOffset) {
if (context.fix) {
// 自动修复:追加声明
rule.append({ prop: 'outline-offset', value: '2px' });
return;
}
report({
message: messages.expected(rule.selector),
node: rule,
result,
ruleName,
});
}
});
};
});
- 在项目 .stylelintrc.js 中启用
module.exports = {
plugins: ['./node_modules/@corp/stylelint-plugin-a11y/lib/index.js'],
rules: {
'corp/a11y-enforce-focus-outline-offset': [true, { fix: true }],
},
};
- 与 husky + lint-staged 联动
"lint-staged": {
"*.{css,scss,less}": "stylelint --fix"
}
保证本地 commit 前自动修复,CI 再次兜底。
- 发布与灰度
先灰度 5% 仓库,收集误报(如第三方库覆写),用 selectorIgnore 选项排除;无误报后全量铺开。
一句话总结:通过自定义 Stylelint 插件,在 AST 层扫描所有含 :focus 的可交互元素,若缺失非零 outline-offset 就报错并自动修复,从而把“焦点可见”做成无法绕过的门禁。
拓展思考
- 如果设计系统使用 box-shadow 模拟焦点环,如何兼容?
答:在插件里再增加一条“box-shadow 必须出现 inset 为 false 且偏移量非零”的校验,或直接把 outline 相关规则关闭,改走自定义的“focus-ring”变量。 - 如何支持 CSS-in-JS?
答:Stylelint 15 已支持解析 styled-components、Emotion 的 template literal,只需把插件放入 extend,配合 @stylelint/postcss-css-in-js 解析器即可。 - 如何给出可视化报告?
答:在 CI 中把 Stylelint 结果输出为 junit.xml,接入阿里 Aone 或腾讯 CI 的“代码红线”面板,让设计师、测试也能看到违规截图。 - 负值 outline-offset 是否一定不可用?
答:在深色毛玻璃背景(如登录浮层)里,设计师常把 outline-offset 设为 -2px,让焦点环内嵌,保持视觉层次。此时需把“非零”细化为“>0 或 <0 均可,但禁止等于 0”,插件正则改为 /^0+px?$/。 - 如何防止开发者用 outline:none 绕过?
答:再加一条规则禁止 outline:none / outline:0,或直接用现有插件 stylelint-a11y 的 outline-focus 规则,与本文插件组合成双保险。