CSS namespacing for Rails controllers and actions

Do you ever find yourself fighting with CSS conflicts in the asset pipeline? Heres’s a handy namespacing trick mentioned by Brian Morearty in his Rails 4.1 Performance Fundamentals course. You can easily apply style rules to all pages of one controller, or specifically target a single action in a controller, by adding the current controller and action as class names to the body tag in your application.html.erb view file:

<body class="<%= request.params[:controller] %> <%= request.params[:action] %>">

Now you can use these generated classes in your style sheets. Let’s say your application is a blog with posts. You can now organize your controller-specific styles like this:

.posts {
  // styles that would affect all pages of the posts controller
} 
.posts.show {
  // styles that would only affect the show action view of the posts controller
}

You can also add a .content class around the yield in application.html.erb to make sure your CSS styles only affect the main part of the page and not the application’s layout:

<div class="content">
  <%= yield %>
</div>
.posts.show .content {
  // styles that would only affect the posts show page content and not the layout 
}

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *