如何校验拖拽生成的绝对定位未使用栅格?
解读
国内低代码/可视化搭建平台盛行,运营、产品同学通过拖拽即可产出页面。平台底层往往把组件的 left/top 直接写成内联样式,导致大量「绝对定位 + 固定像素」代码混进仓库。对研发而言,这类代码既无法响应栅格体系,也难以维护。Stylelint 作为样式守门员,必须能「识别并拦截」这类场景,倒逼拖拽产物改用栅格类名或 CSS Grid/Flex 布局。考点聚焦在「如何写一条自定义规则,精准识别绝对定位且未使用栅格」。面试官希望听到:PostCSS AST 遍历思路、规则命名、自动修复能力、与搭建平台的结合落地。
知识点
- PostCSS AST 节点类型:Declaration(属性)、Rule(选择器)、AtRule(媒体查询等)
- 绝对定位判定:position 值为 absolute 或 fixed
- 栅格使用判定:出现行内 left/top/bottom/right/width/height 之一,即认为「脱离栅格」;若选择器同时包含 .col-、.row、.span-、.grid-、.el-col-(Element Plus)、.ant-col-*(Ant Design)等类名,则视为「已用栅格」
- Stylelint 自定义规则骨架:createPlugin → 返回 { ruleName, rule },rule 函数接收 root、result 参数
- 上下文缓存:用 WeakMap 记录同一 Rule 节点内是否已报过错,避免重复提示
- 自动修复:提供 fix 函数,把 left/top 改为 margin-left/margin-top 并追加 .col 类名,或直接删除绝对定位
- 国内落地:规则包发布到私有 npm,在「搭建平台导出代码」的 Git 仓库里强制走 husky + lint-staged,一旦触发规则即阻断 push,并发送飞书/企业微信机器人提醒拖拽方整改
答案
- 新建规则文件 stylelint-plugin-no-absolute-without-grid
const stylelint = require('stylelint');
const { pluginNamespace } = stylelint.utils;
const ruleName = 'plugin/no-absolute-without-grid';
const messages = stylelint.utils.ruleMessages(ruleName, {
rejected: '绝对定位元素须使用栅格类名,禁止硬编码 left/top',
});
const gridClassRegex = /(?:^|\s)(col|row|span|grid|el-col|ant-col)-/;
module.exports = stylelint.createPlugin(ruleName, function(primaryOption, secondaryOption = {}, context) {
return (root, result) => {
root.walkDecls('position', decl => {
if (decl.value !== 'absolute' && decl.value !== 'fixed') return;
const rule = decl.parent;
// 选择器里是否已有栅格类
if (gridClassRegex.test(rule.selector)) return;
// 是否同时出现 left/top/bottom/right/width/height
const hasAbsoluteMetrics = ['left', 'top', 'right', 'bottom', 'width', 'height']
.some(prop => rule.some(child => child.type === 'decl' && child.prop === prop));
if (!hasAbsoluteMetrics) return;
if (context.fix) {
// 简单修复:把 left/top 改为 margin-left/margin-top,并追加 .col
rule.walkDecls(['left', 'top'], d => {
d.prop = d.prop === 'left' ? 'margin-left' : 'margin-top';
});
rule.selector = rule.selector.split(',').map(s => `.col ${s.trim()}`).join(',');
return;
}
stylelint.utils.report({
message: messages.rejected,
node: decl,
result,
ruleName,
});
});
};
});
- 在 stylelint.config.js 中注册
module.exports = {
plugins: ['./stylelint-plugin-no-absolute-without-grid'],
rules: {
'plugin/no-absolute-without-grid': [true, { severity: 'error' }],
},
};
- 与搭建平台结合
- 平台导出代码时自动写入
.stylelintrc并安装私有规则包 - GitHub Actions / GitLab CI 里执行
stylelint "**/*.css",一旦报错 MR 无法合并 - 提供一键修复脚本
stylelint --fix,平台侧点击「合规修复」即可自动改写
拓展思考
- 规则升级:支持 CSS Grid 的
grid-area作为合法栅格;支持行内样式<div style="position:absolute;left:10px">的检测,需配合 stylelint-selector-no-inline - 性能优化:对万行大文件做「只检测 diff 区域」的增量检查,避免全量扫描拖慢 CI
- 业务闭环:把规则报错回传给拖拽平台,平台在组件属性面板高亮「违规」红点,引导非研发用户一键替换为「栅格容器」组件,实现「lint 驱动产品交互」
- 多端场景:小程序 wxss、支付宝 acss 同样走 PostCSS,规则可直接复用,保证拖拽产物在 H5、小程序双端均符合栅格规范