Creating well-organised CSS files is important if you’re building and maintaining a website. I love to keep things simple, so I have just two basic rules for writing well-structured CSS.
1. File Structure
Don’t just throw CSS rules into your file: organise them. I move from the general to the specific, and usually have the position of rules within my CSS files mirror the position of elements in my HTML.
This helps me find specific CSS rules in the future: if I want to change the style of an H1 element near the top of an HTML file, I look for the corresponding rule near the top of my CSS file.
2. Rule Structure
When writing CSS rules for an individual HTML element, I like to follow a set pattern. Rules for display and position come first, followed by rules for margin, padding, border, text alignment, font size, and colour (English spelling there!):
I’m moving from the low-level stuff (where an element is on the page, what its margins are) to the fine detail (what font to use, and in what colour).
It might sound crazy, but with long rule sets this saves me having to actually read each line to find a specific rule. I already know where to look. There’s also less risk of repetition.
In conclusion, ladies and gentlemen
It’s so tempting, when writing any kind of code, to just throw stuff in as long as it works. But if you do this, you’re doing your(future)self a disservice: you’ll come back in three months and find you have to read the whole CSS file to find what you’re looking for.
Structure makes things simpler.