How I organize my CSS
Structuring my CSS code around newly supported CSS nesting.
There is now browser support across the board (for more recent versions), for both CSS nesting, and using variables. Both of these allow for a better way to structure your CSS and keep it more manageable while making changes to it.
Excited about the nesting support, I decided to refactor the CSS for a couple of the sites I make updates to regularly: the one you're reading this from, and the promo site for Blocks Edit.
Breaking things down and categorizing
I use a global CSS file for a website with separate files for website sections that have considerable additions, like a blog. Those added CSS files are called in only on those sections. I often consider the homepage as its own section, along with certain landing pages that have a good amount of design elements that are specific to it.
These are the general categories I break my CSS code down in:
- Global - variables, any needed resets, and body options
- Text formatting - including for titles, and link properties
- Layout - container and CSS grid layout setup for columns
- Utilities - design patterns, like image and video formatting, buttons, forms, notices, share links, code example formatting, etc
- Header and footer - along with their navigation
I will also have an area in the global CSS file that has the styling for secondary pages that its used on a lot.
Additional details
One thing to consider with nested CSS is not overusing it, leaning towards a flatter structure, allowing elements to be more modular on their own.
Besides nesting my elements and classes, the biggest noticeable change I made along the way was putting @media
declarations for both mobile and dark mode within individual elements instead of separating them into their own mobile and dark mode categories (which is why they're not on the list above).
Global variables I mainly use for the site's standard colors and fonts. If I need to use them at any point, referencing the variables makes it easier than searching for the correct values every time.
Keeping track of what CSS is being used (and where) and what isn’t can be tricky but I’ve found that the above format helps with this. When I make an update to a page, if I end up changing its design considerably, I end up first going to its section CSS where I can either modify currently used CSS, or remove it if I’m no longer using it.
For examples of this approach, here is the global CSS for this site. And the global CSS for the Blocks Edit website.
I've also been working on a boilerplate template that's on GitHub that you can refer to which follows the methods above as well.
Thanks for reading! Consider sharing this post with others: copy this link, or send an email. And follow my updates to get my latest posts.