DEV Community

Cover image for  Automate sorting declarations in just 4 steps
Jose Mendoza
Jose Mendoza

Posted on

Automate sorting declarations in just 4 steps

First off, it should work with CSS, PostCSS, Less and SCSS (but I just tested CSS) and it is also available on Sublime Text, Atom and Emacs (but this post only covers VsCode).

Let's start! I'm working on my projects at freeCodeCamp Responsive Web Design's Certification and started to ask in my head: is writing random stuff on my CSS files the only way to do it? I mean, shouldn't it be ordered in some way? Aren't there ways to order CSS properties out there?.

After some googling found an article covering the topic where there was a particular response that caught my attention and made me think even further about it. I kept searching and found a great post in this community and yeah, after all, there wasn't one but many (random, alphabetically, in groups and probably more I'm not even aware of yet).

So I found myself wanting to give a try to SMACSS and thinking: what about automating the process? Sorting each file manually probably isn't the best idea (I couldn't even imagine following this approach in a large codebase), there must be an efficient way to handle this! Again, after some more googling found a great VSCode extension called PostCSS Sorting that do the job and also an awesome article explaining an implementation with it.

What I did:

Step 1:

Installed PostCSS Sorting extension on VsCode by:

  • Pressing Ctrl + P
  • Pasting this: ext install mrmlnc.vscode-postcss-sorting
  • Pressing Enter key

Step 2:

Edited settings.json (there is a good guide with many methods. I used the first, so:

  • went to File -> Preferences -> Settings (you could just press Ctrl+Comma as well) -> Extensions -> PostCSS Sorting Configuration -> "Edit in settings.json"

Step 3:

Replaced the default "postcssSorting.config": {} with this code because:

  • It corresponds to the most recent smacss.json version at the time of writing
  • (don't worry if you prefer to use others!)

Step 4:

Saved changes and tested:

  • Went to a CSS file
  • Pressed F1
  • Searched for "PostCSS Sorting: Run"
  • Pressed Enter key

Step 5 (extra):

  • Enjoy

I'm combining it with Prettier (for formatting) but I'm curious about your preferred way to do all that stuff! Feel free to share which it is and why in the comments. Thanks for reading.

Top comments (2)

doctorderek profile image
Dr. Derek Austin 戊

This seems pretty neat, but is there any easy way to sort the actual selectors? Honestly the rules being in order I could take it or leave, but it's tricky to fix a bloated stylesheet when rules are duplicated.

colocodes profile image
Damian Demasi

This works great. Thanks!