CSS属性顺序无强制规范,但团队协作推荐“从外到内、从结构到表现”分组排序,如定位布局→盒模型→排版文字→视觉表现→交互状态,并用stylelint+postcss-sorting自动化维护。

CSS 属性顺序有没有强制规范?
没有浏览器或 CSS 标准强制要求属性顺序,display 写在最后和写在最前,渲染结果完全一样。但团队协作中,一致的顺序能显著降低视觉扫描成本——你不用在 margin 和 padding 之间来回跳着找 background-color。
主流可落地的排序策略:按盒模型 + 渲染流分组
推荐采用“从外到内、从结构到表现”的逻辑分组,而非字母序(z-index 排最前这种反直觉方式容易出错)。主流方案如 Airbnb CSS Guide 和 CSS Remedy 都倾向以下分组(每组内不强求顺序,但组间保持固定):
-
定位与布局:
position、top、right、bottom、left、z-index、display、float、clear -
盒模型:
box-sizing、width、height、max-width、max-height、min-width、min-height、margin、padding、border、outline -
排版与文字:
font、font-size、line-height、color、text-align、vertical-align、white-space -
视觉表现:
background、background-color、opacity、filter、box-shadow、transform -
交互与状态:
cursor、user-select、pointer-events、transition、animation
自动化比手动更可靠:用 stylelint + postcss-sorting
靠人眼维持顺序极易遗漏,尤其改样式时只动一两个属性。用工具固化规则才是可持续方案:
- 安装插件:
npm install --save-dev stylelint postcss-sorting
- 在
.stylelintrc.js中启用排序规则:module.exports = { plugins: ['stylelint-order'], rules: { 'order/order': [ 'custom-properties', 'declarations' ], 'order/properties-order': [ // 按上面分组顺序写具体属性名 'position', 'top', 'right', 'bottom', 'left', 'z-index', 'display', 'box-sizing', 'width', 'height', 'margin', 'padding', 'border', 'font', 'font-size', 'line-height', 'color', 'text-align', 'background', 'opacity', 'box-shadow', 'transform', 'cursor', 'transition', 'animation' ] } }; - 编辑器保存时自动排序(VS Code 需装
Stylelint插件并开启editor.codeActionsOnSave)
容易被忽略的三个细节
即使用了工具,这些点仍常导致意外:
立即学习“前端免费学习笔记(深入)”;
-
@media嵌套内部的属性顺序,需单独配置postcss-sorting的insideAtRule选项,否则媒体查询里属性不会被排序 -
background是简写属性,若同时写了background和background-color,后者会被前者覆盖——排序不能掩盖逻辑冲突 - CSS Custom Properties(
--my-var)默认排最前,但若混用var(--my-var)在其他属性值中,工具无法感知依赖关系,得靠人工检查
顺序本身不解决 bug,但它让 bug 更容易被发现。比如 display: none 被写在 transform 后面,人眼扫过去会立刻意识到“这个 transform 其实没机会执行”。










