- Published on
CSS Property Sorting with PostCSS
CSS Property Sorting with PostCSS
What?
Using PostCSS with css-declaration-sorter to automatically sort CSS properties in a consistent, logical order.
Why?
No more fighting with formatters or manually organizing CSS properties. Every CSS file stays consistent automatically.
How It Works
When you run npm run sort-css, PostCSS processes all .css files in your src directory and sorts their properties according to the SMACSS order:
Positioning → Box Model → Typography → Visual → Misc
This means layout properties (display, grid-template-columns) appear first, followed by spacing, then typography, then colors and backgrounds.
Setup
1. Install Dependencies
npm install --save-dev postcss postcss-cli css-declaration-sorter
2. Create postcss.config.cjs
module.exports = {
plugins: [
require('css-declaration-sorter')({
order: 'smacss', // Options: 'smacss', 'alphabetical', 'concentric-css'
keepOverrides: true, // Prevents breaking shorthand/longhand relationships
}),
],
}
3. Add NPM Script
In your package.json:
{
"scripts": {
"sort-css": "postcss 'src/**/*.css' --replace --no-map"
}
}
Usage
Manual Sorting
Run this command anytime to sort all CSS files:
npm run sort-css
Automatic on Save (VS Code/Trae)
- Install the VS Code PostCSS Sorting extension
- Add to
.vscode/settings.json:
{
"postcssSorting.config": {
"order": "smacss"
},
"[css]": {
"editor.formatOnSave": true,
"editor.defaultFormatter": "mrmlnc.vscode-postcss-sorting"
}
}
Available Sorting Orders
| Order | Description | Example Priority |
|---|---|---|
| SMACSS (recommended) | Groups by function: Box → Border → Background → Text → Other | display before color |
| Alphabetical | Simple A-to-Z ordering | background before display |
| Concentric CSS | Outside-in: Positioning → Box model → Dimensions → Text | position before margin |
Example
Before:
.card {
color: #333;
display: grid;
margin: 1rem;
grid-template-columns: 1fr 1fr;
background: #fff;
font-size: 14px;
}
After (SMACSS):
.card {
/* Positioning & Layout */
display: grid;
grid-template-columns: 1fr 1fr;
/* Box Model */
margin: 1rem;
/* Typography */
font-size: 14px;
color: #333;
/* Visual */
background: #fff;
}
Notes
- Works with CSS only (not SCSS)
- The
.cjsextension is required if your project uses ES Modules ("type": "module"inpackage.json) - Runs on all
.cssfiles insrc/**/*.css- adjust the path in the script if needed - There is no postcss sorting plugin for TRAE (my prerferred flavor, thank to AI). Hence, I use stylelint + stylelint-order or above method as a precommit hook.
Now all your CSS files stay perfectly organized with zero effort.
Discuss on Twitter • View on GitHub