How to manage CSS Stylesheet Assets in Rails 3.1?

Ben picture Ben · May 23, 2011 · Viewed 11.1k times · Source

I'm just learning the new asset pipeline in Rails 3.1. One particular problem I'm having is with the way Sprockets just mashes all the found CSS stylesheets into one massive stylesheet. I understand why this is advantageous over manually merging stylesheets and minifying for production. But I want to be able to selectively cascade stylesheets instead of having all rules all mashed together. For instance, I want:

master.css

to be loaded by all pages in the Rails app, but I want

admin.css only to be loaded by pages/views within the admin section/namespace.

How can I take advantage of the great way that Rails 3.1 combines stylesheets and minifies them for production, but also have the former flexibility of being able to load only certain stylesheet combinations per layout?

Or should this be done by adding a class to body tags in layouts-

body class="admin"

And then target style rules as appropriate. Using SASS scoped selectors this might be a reasonable solution.

Answer

zeeraw picture zeeraw · May 29, 2011

This is how i solved the styling issue: (excuse the Haml)

%div{:id => "#{params[:controller].parameterize} #{params[:view]}"}
    = yield

This way i start all the page specific .css.sass files with:

#post
  /* Controller specific code here */
  &#index
    /* View specific code here */
  &#new
  &#edit
  &#show

This way you can easily avoid any clashes.

Hope this helped some.