controller/action specific CSS - Part 2

I wrote a previous entry about a pattern for making CSS rules specific to controllers and actions.

Unfortunately this didn’t work in IE. Here is an alternative solution, which is cross-browser compatible:


<body id="<%= controller.controller_name %>" class="action-<%= controller.action_name %>">

(I chose to prefix the action name with action, to avoid any potential namespace contamination )

Here are the new CSS rules:

body#register {} /* all actions in controller */
body#register.action-step_1 {} /* only step_1 action */

controller/action specific CSS

Here’s a trick that I use to put styles on specific pages, or even better on all the pages in a specific controller—with no extra markup needed!

I call them “controller specific” CSS rules.

In the layout template, I give the body tag a name that is based on the controller attributes:
<body id="<%= "#{controller.controller_name}-#{controller.action_name} %>">
Now in the CSS I can give rule to any of the registration pages pages (for instance relating to register_controller.rb):
body[id|=register] { width: auto; }
You can also give a rule to a specific page
body[id|=register-step_1] { width: auto; }

For more info, see W3C CSS 2.1 Spec 5.8.1

actionmailer ActionView ajax alphadecimal audio autotest BDD blocks capistrano ssh ruby controller css dashboard widget delegate dog puppy naming name DRM email obfuscation exceptions factory pattern filemerge find and replace finder fink fixtures fun gem google maps helper helpers imagemagick Intertrust javascript logo math meetup model openssl OS X patch Pioneer Electronics plugin polymorphism prototype.js rails rake rmagick RSA encryption ruby script shoulda subversion SyncTV TDD testing textmate tricks unique hashes unix shell validation view yaml zebra stripes