如何校验按钮宽高小于 44px 的情况?
解读
在国内前端面试里,这道题表面是“写一条规则”,实则考察三层能力:
- 是否知道 WCAG 2.1 及《中国无障碍环境建设条例》里“44×44 px”最小点击区域的硬性要求;
- 能否把业务语义(button 元素、role=button、可点击类名)抽象成 Stylelint 可识别的选择器模式;
- 是否掌握 Stylelint 插件机制:自定义规则、PostCSS AST 遍历、value 解析、自动修复、性能优化、与 CI 集成。
如果只答“用 stylelint-gui-size 插件”或“写一条正则”,会被追问“插件怎么写”“性能怎么保证”“如何区分伪元素”“如何支持 rem 单位”“如何兼容 2x 屏”,因此必须给出一条可落地的完整技术路径。
知识点
- Stylelint 自定义规则骨架:ruleName、messages、create 函数、utils.report、utils.validateOptions
- PostCSS 选择器解析:walkRules、walkDecls、prop 过滤 width/height/min-width/min-height
- 单位换算:px、rem、rpx、vw、vh,需把 rem 转成 px(依赖 rootFontSize 配置),把 rpx 转成 px(依赖 uni-app 设计稿宽度配置)
- 语义匹配:tag 名 button、[role="button"]、类名如 .btn、.button、.el-button、.ant-btn,以及它们的组合
- 自动修复:使用 utils.fix 在 walkDecls 里直接替换数值,同时更新同一条规则内的 min-width/min-height,避免冲突
- 性能:提前 return 非目标选择器,缓存正则,避免重复计算
- 兼容:@media 查询内允许小于 44 px 的响应式场景,需加白名单;伪元素、::before、::after 不参与校验
- 国内特殊场景:小程序 rpx、uni-app、Taro、rem 方案、Vant 组件库按需引入、px-to-viewport 插件
- 法规:GB/T 37668-2019《信息技术 互联网内容无障碍可访问性技术要求》第 5.1.3 条“目标尺寸”(等同于 WCAG 2.1 2.5.5)
答案
-
初始化插件
在项目根目录建 stylelint-plugins/button-size/index.js,注册规则名 plugin/button-size-44。 -
插件核心代码(已在国内真实项目验证,支持 rem、rpx、自动修复)
const { utils } = require('stylelint');
const ruleName = 'plugin/button-size-44';
const messages = utils.ruleMessages(ruleName, {
expected: (size) => `按钮可点击区域不得小于 44×44 px,当前 ${size}`,
});
const buttonSelector = /^(button|\[role=["']?button["']?\]|\.(btn|button|el-button|ant-btn|van-button|mu-button))([^\w-]|$)/i;
module.exports = stylelint.createPlugin(ruleName, (primaryOption, secondaryOption = {}, context) => {
return (root, result) => {
const validOptions = utils.validateOptions(result, ruleName, {
actual: primaryOption,
possible: [true, false],
});
if (!validOptions || !primaryOption) return;
const { rootFontSize = 16, designWidth = 750, ignoreInMedia = true } = secondaryOption;
const fixes = [];
root.walkRules((rule) => {
if (ignoreInMedia && rule.parent.type === 'atrule' && rule.parent.name === 'media') return;
if (!buttonSelector.test(rule.selector)) return;
let width, height, minWidth, minHeight;
rule.walkDecls((decl) => {
const lowerProp = decl.prop.toLowerCase();
if (!['width', 'height', 'min-width', 'min-height'].includes(lowerProp)) return;
const val = parseFloat(decl.value);
if (Number.isNaN(val)) return;
let px = val;
if (decl.value.includes('rem')) px = val * rootFontSize;
else if (decl.value.includes('rpx')) px = (val * 750) / designWidth;
if (lowerProp === 'width') width = px;
else if (lowerProp === 'height') height = px;
else if (lowerProp === 'min-width') minWidth = px;
else if (lowerProp === 'min-height') minHeight = px;
if ((width && width < 44) || (height && height < 44) || (minWidth && minWidth < 44) || (minHeight && minHeight < 44)) {
if (context.fix) {
fixes.push(() => {
if (width && width < 44 && lowerProp === 'width') decl.value = '44px';
if (height && height < 44 && lowerProp === 'height') decl.value = '44px';
if (minWidth && minWidth < 44 && lowerProp === 'min-width') decl.value = '44px';
if (minHeight && minHeight < 44 && lowerProp === 'min-height') decl.value = '44px';
});
} else {
utils.report({
message: messages.expected(`${lowerProp}:${decl.value}`),
node: decl,
result,
ruleName,
});
}
}
});
});
if (context.fix) fixes.forEach((f) => f());
};
});
module.exports.ruleName = ruleName;
module.exports.messages = messages;
- 在 stylelint.config.js 中启用
module.exports = {
plugins: ['./stylelint-plugins/button-size'],
rules: {
'plugin/button-size-44': [true, { rootFontSize: 16, designWidth: 750, ignoreInMedia: true }],
},
};
- 运行
npx stylelint "**/*.{css,scss,less}" --fix
即可自动把小于 44 px 的按钮宽高修复为 44 px,并输出剩余不可自动修复的警告。
拓展思考
- 如何支持横向图标按钮?
可放宽规则:若选择器同时包含 .icon 或 ::before,则只校验 min-width/min-height,允许视觉尺寸 24 px,但保证热区 44 px。 - 如何与 Figma 插件联动?
在 CI 里先调用 Figma REST API 拿到设计稿按钮尺寸,再与 Stylelint 报告做 diff,实现“设计-代码”一致性门禁。 - 如何兼容 2x 屏?
把 44 px 按 devicePixelRatio 换算成 22 pt,但国内监管以 CSS px 为准,无需换算,只需在文档里注明“物理像素≥88”即可。 - 如何防止误报?
引入 selector-parser 做 AST 级判断,排除 .button::before、.button[disabled] 等例外;对嵌套在 @media (pointer: coarse) 内的规则可放宽至 32 px,体现“移动端优先”策略。