如何强制 line-height 使用无单位数值?
解读
面试官抛出这条规则,表面看是“写一条配置”,实则考察三方面:
- 对 Stylelint 规则体系的熟悉度——能否第一时间定位到
declaration-property-unit-allowed-list或declaration-property-value-allowed-list; - 对 CSS 层叠规范的掌握——明白带单位 line-height 会继承计算值,而无单位 line-height 继承的是“系数”,从而避免排版灾难;
- 工程化落地经验——能否把规则下沉到团队基线,配套自动修复、git hooks、CI 卡点,让“无单位”成为不可逆的共识。
国内大厂(阿里、字节、美团)的样式基线里,这条规则属于“必开红线”,答不出直接降档。
知识点
- Stylelint 规则分类:Possible Errors、Limit Language Features、Stylistic Issues;本题属于 Limit Language Features。
- 关键规则:
–
declaration-property-unit-disallowed-list:直接禁止 line-height 带单位; –declaration-property-value-allowed-list:用正则表示仅允许纯数字、小数及小数点; –function-disallowed-list:防止有人用 calc(24px) 绕过。 - 自动修复:Stylelint 14+ 支持
--fix,但上述两条规则本身不自带 fix,需要自定义插件或写 PostCSS 插件把 px/pt/em 计算成无单位数值。 - 国内落地配套:
– VS Code 插件
stylelint.vscode-stylelint开启autoFixOnSave; – GitHub Actions/阿里 Flow 在 PR 阶段npx stylelint "**/*.{css,scss,less}" --max-warnings 0; – 与 commitlint 联动,husky 拦截提交。
答案
-
安装依赖
npm i -D stylelint stylelint-config-standard-scss -
在
.stylelintrc.js中追加module.exports = { extends: ['stylelint-config-standard-scss'], rules: { // 方案A:直接禁止 line-height 带任何单位 'declaration-property-unit-disallowed-list': { 'line-height': ['px', 'pt', 'em', 'rem', '%'] }, // 方案B:更严格,只允许数字、小数点 'declaration-property-value-allowed-list': { 'line-height': [/^\d+(\.\d+)?$/] }, // 防止 calc 绕过 'function-disallowed-list': ['calc'] } }; -
自动修复(可选) 若团队要求
--fix直接抹掉单位,可写自定义插件stylelint-plugin-line-height-unitless,核心逻辑:const { createPlugin } = require('stylelint'); const { parse } = require('postcss-values-parser'); const ruleName = 'plugin/line-height-unitless'; const messages = createPlugin.ruleMessages(ruleName, { rejected: 'line-height 必须是无单位数值' }); const plugin = createPlugin(ruleName, (enabled) => (root, result) => { if (!enabled) return; root.walkDecls('line-height', (decl) => { const val = parse(decl.value); val.walkType('word', (node) => { if (node.unit && node.unit !== '') { if (decl.variable && decl.prop.startsWith('--')) return; // 跳过 CSS 变量 const num = parseFloat(node.value); if (!Number.isNaN(num)) { // 自动修复 node.value = String(num); node.unit = ''; decl.value = val.toString(); } createPlugin.report({ message: messages.rejected, node: decl, result, ruleName }); } }); }); }); module.exports = plugin;注册后在
.stylelintrc.js的plugins数组里引入,并打开plugin/line-height-unitless: true,即可npx stylelint --fix。
拓展思考
- 设计 token 时代如何兼容无单位 line-height?
把 line-height 抽成 CSS 变量
--lh: 1.5,在组件层统一引用,既满足规则又支持主题切换。 - 低代码平台动态拼接样式怎么办? 在运行时拼接字符串阶段,先走 Stylelint 的 Node API 做 lint,不通过直接阻断发布,避免“拼接一时爽,线上火葬场”。
- 老项目存量带单位代码如何批量迁移?
用 PostCSS 插件扫描所有 line-height,把 px 值除以父级 font-size 得到系数,再写回源码,最后 git commit 自动生成
refactor: line-height 统一无单位的标准化 message,方便 CR 追溯。