什么是 CSS 格式化?
CSS 格式化是为层叠样式表添加一致缩进、换行和空格的过程,目的是让代码对人类可读。浏览器完全忽略 CSS 中的空白字符。压缩成一行的样式表和整齐缩进的样式表在渲染效果上完全相同。两者的区别在于可读性:格式化后的 CSS 让你一眼扫清选择器、发现缺失的分号,并直观理解层叠关系。
CSS 格式化工具(有时也称为 CSS 美化工具或代码美化器)将压缩或格式不一致的 CSS 重写为统一缩进、每行一条声明、大括号位置一致的形式。这是压缩操作的逆过程,也称为美化或格式化输出。压缩操作通过删除空白字符来减小生产环境的文件体积,而格式化则为开发、代码审查和代码库维护恢复代码结构。
CSS 规范(W3C CSS 语法模块第 3 级)定义了样式表的语法,但对空白字符惯例没有任何规定。格式化规则由团队决定:制表符还是空格、2 个还是 4 个空格的缩进、大括号风格、规则集之间是否留空行。格式化工具统一执行你选择的惯例,适用于每一个文件。大多数团队将惯例写入 .prettierrc 或 .editorconfig 文件。
为什么使用这款 CSS 格式化工具?
粘贴任意 CSS,毫秒内即可获得缩进整齐的输出。无需安装编辑器插件,无需编写配置文件,无需创建账户。
CSS 格式化工具使用场景
CSS 属性排序参考
大多数 CSS 格式化工具不会重新排列属性顺序。但许多代码风格指南建议将相关属性归类在一起。下表展示了 Stylelint 的 order 插件和 CSScomb 等工具所使用的常见分组惯例:
| 分组 | 示例属性 | 用途 |
|---|---|---|
| Position & Layout | position, display, float, clear | Defines the element's rendering mode |
| Box Model | width, height, margin, padding | Controls dimensions and spacing |
| Typography | font-size, line-height, color | Text styling properties |
| Visual | background, border, box-shadow | Decorative properties |
| Animation | transition, animation, transform | Motion and transform effects |
| Misc | cursor, overflow, z-index | Behavioral and stacking properties |
此分组是一种惯例,并非 CSS 的强制要求。浏览器根据优先级和来源顺序应用声明,与规则块内属性的位置无关。格式化工具专注于空白字符和缩进;属性重排是一个独立的代码检查问题,由 Stylelint 等工具负责处理。
CSS 格式化与 CSS 压缩的对比
格式化与压缩是互逆的操作,分别应用于开发流程的不同阶段:
代码示例
如何在不同语言和环境中以编程方式格式化 CSS:
import * as prettier from 'prettier'
const ugly = 'body{margin:0;padding:0}h1{font-size:2rem;color:#333}'
const formatted = await prettier.format(ugly, {
parser: 'css',
tabWidth: 2,
singleQuote: true,
})
// → "body {\n margin: 0;\n padding: 0;\n}\n\nh1 {\n font-size: 2rem;\n color: #333;\n}\n"import cssbeautifier
ugly = 'body{margin:0;padding:0}h1{font-size:2rem;color:#333}'
opts = cssbeautifier.default_options()
opts.indent_size = 2
formatted = cssbeautifier.beautify(ugly, opts)
# → "body {\n margin: 0;\n padding: 0;\n}\n\nh1 {\n font-size: 2rem;\n color: #333;\n}"# Format a single file in place
npx prettier --write styles.css
# Format all CSS files in a directory
npx prettier --write "src/**/*.css"
# Check formatting without modifying files
npx prettier --check "src/**/*.css"
# Pipe minified CSS through stdin
echo "body{margin:0;padding:0}" | npx prettier --parser css<?php
// composer require sabberworm/php-css-parser
require 'vendor/autoload.php';
use Sabberworm\CSS\Parser;
use Sabberworm\CSS\OutputFormat;
$input = 'body{margin:0;padding:0}h1{font-size:2rem;color:#333}';
$document = (new Parser($input))->parse();
echo $document->render(OutputFormat::createPretty());
// → body {
// margin: 0;
// padding: 0;
// }
// h1 {
// font-size: 2rem;
// color: #333;
// }