Applying SMACSS to Rails projects

Portland

SMACSS is a style guide for organizing CSS in reusable modules. This makes a lot of sense for teams that are collaborating in a big project. How do we apply it in our Rails projects?

SMACSS Principles

SMACSS (Scalable and Modular Architecture for CSS) is a set of rules created and promoted by Jonathan Snook, who also offers a book with the same name. A good part of this book can be found for free on http://smacss.com. If you don’t know what SMACSS is I recomend reading this book, it’s a quick read.

SMACSS basic principles are:

  • Base are default styles of HTML elements (p, a, ul, li …)
  • Layout are styles used generally for layout. Are always prefixed by -l (e.x. l-sidebar)
  • All remaining CSS goes in modules and each goes prefixed with the namespace of the module to which it belongs. example, an alert module could have the following classes .alert, .alert-message, .alert-icon.

These practices are highly encouraged:

  • Don’t use ID in CSS
  • Minimize the deepness of your selectors
  • Use classes to define visual presentation patterns of your elements.

Implementation styleguide of SMACSS on Rails

File Structure

Files must be structured the following way:

app/assets/stylesheets/
├── application.css.scss
├── base.css.scss
├── layout.css.scss
|
├── globals
│   ├── _all.scss
│   ├── _functions.scss
│   ├── _mixins.scss
│   └── _variables.scss
|
└── modules
    ├── alert.css.scss
    └── ...

Filenames In SASS an underscore prefix indicates that it’s a partial which means that the file wont be compiled to a CSS by itself. SMACSS promotes modules that can be reused independently, so it uses partials only for pure SASS constrctors, like variables, functions or mixins declarations.

The files that can be used independently, (ex. modules) must have the double extension .css.scss. Partials on the other hand must start with _ and must end with the .scss extension. From Rails 4.2 partials that have the extension .css.scss are deprecated.

Application Manifest Use Sprockets’ require syntax //= to specify how style show be merged in a sole stylesheet in production.

//= require normalize
//= require ./base
//= require ./layout
//= require_tree ./modules

Globals This directory is for SASS variables, functions and mixins that are really used globally; If you have variables, mixins or functions and are going to be used in a single module, define them in the module itself, don’t clog the Global with rules that are going to be used only once.

Consider combining all global imports in a single file called globals/_all.scss that looks like:

@import "./variables";
@import "./mixins";
@import "./functions";

Then in your base, layout and module stylesheets you can start importing all global styles in each of the files.

@import "globals/all";