Published on

CSS Property Sorting with PostCSS

Authors
  • avatar
    Name
    Manpreet Bhasin
    Twitter

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:

PositioningBox ModelTypographyVisualMisc

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)

  1. Install the VS Code PostCSS Sorting extension
  2. Add to .vscode/settings.json:
{
  "postcssSorting.config": {
    "order": "smacss"
  },
  "[css]": {
    "editor.formatOnSave": true,
    "editor.defaultFormatter": "mrmlnc.vscode-postcss-sorting"
  }
}

Available Sorting Orders

OrderDescriptionExample Priority
SMACSS (recommended)Groups by function: Box → Border → Background → Text → Otherdisplay before color
AlphabeticalSimple A-to-Z orderingbackground before display
Concentric CSSOutside-in: Positioning → Box model → Dimensions → Textposition 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 .cjs extension is required if your project uses ES Modules ("type": "module" in package.json)
  • Runs on all .css files in src/**/*.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.