Today a friend and I talked about how to organise CSS code, specially on big projects. Here's my way. The goal I try to achieve is to be able to locate the rule I'm interested in as soon as possible.
Splitting into partials
Nowadays I always use a CSS pre-procesor, and my go-to choice is Sass. One cool feature of CSS pre-processors is that you can split your code into smaller files and then merge them all in one single CSS file. Another advantage of this is that re-using code is super-easy (think of common mixins or hacks that you always use).
These smaller files are called partials, and in Sass they are files that begin with an underscore
_. With that, Sass will know that you don't want to generate a CSS file just for them, since they are meant to be imported from other Sass files.
If I'm not using Compass –which I try to avoid if I only need a few things of it–, I put my reset rules in their own partial. I also create a file name
_common.sass, in where I'd write common variables (like colors, font sizes, etc.) and mixins that I think I'll use through the whole project (for instance, a
clearfix hack, or a mixin for rounded plain buttons).
Then I create a single file for each part of the site that has a significantly different appearance.
All of these partials are imported from one single Sass file, which I like to call
Some example of this high-level file splitting:
. ├── _common.sass ├── _fonts.sass ├── _page_regular.sass ├── _page_splash.sass ├── _reset.sass └── main.sass
Inside each partial
I divide each file into sections, and always follow the same order in all my projects"
- "Raw" selectors
- Selectors with
- Selectos with
This organisation is somehow arbitrary, but the actual order / system that you use is not that important – what is important is coherence. If you have a selector like
footer.simple, would you know where to look? That's what matters.
With Sass I also like to use indentation and the
& so everything is kind of grouped together. For instance:
article.post font-size: $font-size-main & > h1 font-size: $font-size-huge font-weight: bold a color: $link-color
Inside each rule
Some CSS rules can get really bloated, so it's good to have a bit of organisation there as well, although I'm way more relaxed here.
I like to include mixins at the top, and then rules that affect to the rendering of the element: position, size, margins…
button.ok +std-button display: inline-block padding: 0.5rem 1rem background: $color-ok
And this is pretty much it :) It's not complicated, but sometimes a bit of organisation can help us to be happier while we code.