How to organize CSS declarations

As you develop your website you might find that some of your CSS selectors will contain so a lot of declarations. So when you need to adjust your padding it can take multiple seconds to spot your padding declaration inside a selector with 20-30 declarations. Sure, you can search, but that takes more operations and keystrokes (position marker at selector, type search command (ctrl-f), type first few letters of declaration, press enter) and shouldn't really be necessary.

Grouping declarations by topic

One solution is to group related declarations together, f.ex. position, top and left. This can work reasonably well. But you can run into cases where it is not obvious which group a declaration belongs to. Will color belong with text declarations like font-size and font-family or with decorative declarations like background-image and background-color? For this to work you need to have strictly defined groups and remember what goes in which group. If not, some declarations will from time to time end up in the wrong group, causing frustration and lost time when you don't find them quickly.

You might also end up with 4-5 groups of declarations inside one rule so it is beneficial to have some organization between the groups. All in all, I think that grouping declarations together by topic can simplify working with stylesheets significantly, but it also requires more discipline and it is hard to keep your groups 100% consistent. So while it works, it is also complicated.

Grouping declarations alphabetically

A different solution to your CSS mess is to sort your declarations alphabetically. This is simple to do but will in some cases lead to code that is a little harder to work with.

When you organize your declarations alphabetically you always know where to put things and where to find them. So it is easy and consistent, two qualities I like.

The downside of alphabetical sorting is that you often adjust two declarations together that are not anywhere near eachother. F.ex. an absolutely positioned element that is positioned with bottom and right. And since b and r are in opposite sides of the alphabet, adjusting these two will be a little more cumbersome than if you grouped your declarations by topic.


I recommend alphabetical sorting because it is simpler and 100% consistent. I believe that these two qualities will save time in the long run over organizing your CSS declarations by topic.

Comments are closed.