跳到主要内容
uencoder

如何Format CSS

美化 CSS with consistent indentation, spacing, and rule ordering.

问题

你的 CSS 是 minified 或 inconsistently formatted, making 它困难到 maintain.

前置条件

  • Understanding 的 CSS syntax
  • 熟悉selectors 和 properties

步骤

  1. 1. Parse the CSS rules

    The formatter parses selectors, declarations, at-rules, and comments. It identifies the structure to apply consistent formatting. Invalid CSS may cause parsing errors.

    输入
    body{margin:0;padding:0}
    输出
    parsed rules
  2. 2. Apply formatting conventions

    Place each declaration on a new line with a semicolon. Indent declarations inside their rule. Add spaces after colons and before opening braces. Sort properties if desired (alphabetical or by category).

    输入
    body{margin:0;padding:0}
    输出
    body {\n  margin: 0;\n  padding: 0;\n}
  3. 3. Handle nested and at-rules

    Modern CSS and preprocessors support nesting and at-rules like @media. Indent nested rules to reflect their hierarchy. Preserve the order of at-rules and their contents.

    输入
    @media(min-width:768px){.x{color:red}}
    输出
    properly nested format

预期结果

Readable CSS 具有 consistent indentation, spacing, 和可选属性 sorting.

常见错误

Formatter breaks vendor prefixes
Ensure the formatter preserves vendor-prefixed properties (-webkit-, -moz-). Some formatters strip them; configure to keep them.
Nested syntax not supported
Use a formatter that supports CSS nesting or your preprocessor syntax (Sass, Less).

排障指引

  • If the formatted CSS behaves differently, check for altered specificity or reordered properties that rely on cascade order.
  • Comments should be preserved; if they disappear, switch formatters.

安全限制

  • Formatting CSS is safe. CSS cannot execute code, though CSS-based exfiltration attacks exist in content injection contexts.

相关工具

参考链接