I haven’t thought about ordering CSS properties in a while, but I began to work on the redesign of HTMHell recently and I decided to challenge my current approach.
How I’m ordering CSS properties now
Honestly, I don’t know. It’s a mix of logical grouping, alphabetical order and just no order at all. It kinda has some structure, but I guess you could describe it as pretty arbitrary.
Here’s a random class from the current HTMHell website.
According to a poll I ran on Twitter, most people order by type, closely followed by alphabetical ordering. I also did a quick search and, as expected, many people have thought and written about different approaches and the pros and cons compared to others.
- Poll Results: How do you order your CSS properties?
- “Outside In” — Ordering CSS Properties by Importance
- How to organize CSS @ 9elements
- Alphabetize your CSS properties, for crying out loud
- Harry Potter and the Order of CSS
- On Declaration Sorting in CSS
My new approach
Since I don’t have a strong opinion on the topic and I haven’t tried different techniques, I will not repeat what others have done already, I’ll just share how I’ll try to write CSS on the new HTMHell website. Switching to a completely new system feels a bit too radical, so I decided to refine and structure my current approach.
I’m against grouping all properties, because it’s hard to group all of them sensibly and it’s hard to remember later which properties go together. I’m also against ordering alphabetically because I want
right close to
align-items close to
display. I want strict ordering for properties I use a lot and a loose but structured ordering for the rest. I work my way from the outside in, from the back to the front.
- Box model properties
- Everything else, in alphabetical order
Here’s an example:
/* box model */
padding: 2rem 1rem;
/* background */
/* layout */
/* type */
/* other, in alphabetical order */
box-shadow: 2px 2px 2px 2px #000;
transition: all 0.3s;
If I notice that I’m using a property from the 5th group a lot, I might promote it to one of the other groups. Grouping and sorting is probably unnecessary on such a small site like the one I’m working on right now, but it’s an interesting exercise. If It works here, I might try it at work on a larger project with more people involved. If not, I’ll just keep doing whatever feels right to me. 🙃