Structuring your SASS files
I’ve been using SASS for a little while now and I find one of the biggest advantages of using it is to help organise my CSS into a meaningful and manageable structure.
Breaking your CSS into smaller components not only help your CSS code base (nobody like digging through 2000+ lines of CSS) but also helps you think a lot more about what makes for a good, modular, component and how to make your code DRY and reusable.
I find myself using the following structure for small and large projects alike, it might be a little over-the-top for some smaller projects, but it makes for good practice:
scss/
├── components/ (Reusable blocks of components)
│ ├── alert/
│ | ├── _alert.scss
│ | ├── _alert-overlay.scss (A variation of the alert component)
│ ├── ...
├── core/ (Basic HTML elements)
│ ├── forms/
│ | ├── _input.scss
│ | ├── _select.scss
│ | ├── ...
│ ├── helpers/
│ | ├── _helpers.scss (General hide, remove, float-left etc classes)
│ ├── typography/
│ | ├── _headings.scss
│ | ├── _lists.scss
│ | ├── ...
├── layouts/ (Common template layouts)
│ ├── columns/
│ | ├── _columns-two.scss
│ | ├── _columns-three.scss
│ | ├── _wide.scss
│ | ├── _wide-banner.scss
│ │ ├── ...
├── vendor/ (CSS or SASS from 3rd parties)
│ ├── normalize/
│ | ├── _normalize.scss
│ ├── ...
_functions.scss (Global SCSS functions)
_vars.scss (Global SCSS variables)
print.scss
style.scss (All of the mixins are imported into this file)
Occasionally I might have the folder /scss/templates/
, but I try to avoid template specific code when possible; Ideally everything should be self-contained and reusable, but sometimes there are exceptions that require page specific styling.
Within each SASS file you will find several mixins for different media queries, something like this:
// Alert
@mixin alert-mobile {
.alert {
...
}
} // end mixin
@mixin alert-tablet {
.alert {
...
}
} // end mixin
...
These are then included in the style.scss file:
// Styles
@import "components/alert/alert";
...
@media only screen {
@include alert-mobile;
...
} // end media
@media only screen and (min-width: $breakpoint_tablet) {
@include alert-tablet;
...
} // end media
Hopefully you get the idea.
This structure might not be suitable for everyone, but I find it works really well for me. I can find and focus on a specific component easily and know the styles within that SASS file are specific to that component only. Even better, when this structure is combined with a coding styleguide | library | documentation (a topic for another time), it makes modular development, documentation and scalability easier to manage.