CSS is often treated as a second-class citizen compared to JavaScript in terms of code style and formatting. But a codebase with inconsistently formatted CSS is harder to read, harder to review, and harder to merge in pull requests. Adopting a consistent formatting style and enforcing it automatically improves the quality of CSS the same way consistent JavaScript formatting does.
Key CSS Formatting Conventions
One property per line: each CSS property declaration should appear on its own line. This makes diffs more readable (changing one property produces a one-line diff instead of a full rule diff) and makes it easier to scan a rule for a specific property.
Consistent indentation: use either 2 or 4 spaces consistently throughout the project. Tabs are acceptable if your team uses them, but be consistent.
Space after the colon: color: red not color:red. The space improves readability at a glance.
Opening brace on the same line as the selector: .my-class { is the standard convention. Some teams use the next-line brace style but same-line is more common in CSS.
Closing brace on its own line: end every rule with } on a line by itself.
Blank lines between rules: separate distinct rule blocks with one blank line for visual grouping.
Property Ordering
Property ordering within a rule is a matter of convention. Two popular approaches are alphabetical order (easy to automate and search but groups unrelated properties) and grouped by category (positioning first, then box model, then typography, then visual and decorative properties last).
Some teams use a specific order defined in a tool like Stylelint's order plugin. Consistency matters more than which order you choose.
Using the DevHexLab CSS Formatter
Open the tool at /tools/css/css-formatter. Paste minified or poorly formatted CSS. The tool applies standard formatting with correct indentation, spacing, and line breaks. Copy the formatted result.
Frequently Asked Questions
What is the best CSS linter?
Stylelint is the most widely used CSS linter. It can enforce formatting rules, property ordering, naming conventions, and best-practice rules.
Can I run CSS formatting automatically on save?
Yes. Most code editors support running Prettier (which handles CSS formatting) on save via the Format on Save setting.
Format CSS as consistently as JavaScript.