Clean up, clean up.
In the spirit of getting stuff done, CSS often takes a back seat when you’re building a new Rails application – and you can quickly end up with a messy CSS code base. At Chloe + Isabel, our technical debt has accumulated to the point where it’s time to roll up the sleeves and perform some CSS surgery.
Let’s start with the file structure. In Rails fashion, I wanted to create a convention that our development team can use that is familiar, flexible and has a minimal learning curve. So I tried to mimic Rails conventions as much as possible.
File Structure:
- app/stylesheets
- production.sass (this is the only file included by the layout, like a Rack endpoint)
- base_styles/ (these are the building blocks of your application, like ActionController)
- reset.sass
- colors.sass
- forms.sass
- errors.sass
- products.sass
- sidebar.sass
- application.sass (acts like application_controller.rb)
- mixins/ (styles that keep your code DRY. kind of like ActiveSupport)
- round_corners.sass
- utils.sass (clearfix and similar site-wide utilities)
- views/ (follows the Rails app/ directory structure)
- frontend.sass
- backend.sass
- controller.sass
- controller/
- action.sass
Add class attributes to <body> that map to controllers and actions.
We can manage controller and action specific CSS by adding class attributes to the <body> tag.
<body class=”#{params[:controller].paramaterize}
#{params[:controller].paramaterize}-#{params[:action].paramaterize}”>
In the example below, the cart action in the OrdersController overrides the default product text color.
The body tag in our layout will look like:
<body class=”orders orders-cart”>
base_styles/products.sass (This is the base product style across the application.)
.products (base style)
color: red
views/orders.sass You can override styles by controller.
.orders (controller)
.products (base style)
color: purple
views/orders/cart.sass You can override styles by action.
.orders (controller)
.orders-cart (action)
.products (base style)
color: green
Just the beginning…
Finding the right structure that works for our team will be an ongoing process, so here are a few topics I plan to elaborate on:
- Using base styles vs. application.sass
- Naming color variables
- Pattern libraries
- and other issues we run into…
References: