Ruby on Rails
HowtoCorrectlyUseStylesheetsInYourTemplates

CSS style sheets should be put in the public/stylesheets directory of your Rails application.

Let’s assume you have a stylesheet called cookbook.css, located at public/stylesheets/cookbook.css

There are two ways to include it in your rhtml:

1. Using normal HTML, like so:

<link rel="Stylesheet" href="/stylesheets/cookbook.css" type="text/css" media="screen" />

Or if you wanted to hide the stylesheet from Netscape 4:

<style type="text/css" media="screen">
  @import url(/stylesheets/cookbook.css);
</style>

2. Using rails code, like so:

<%= stylesheet_link_tag "cookbook" %>

This will render HTML code to the page similar to above automatically. You don’t need to add the .css at the end of the file name, Rails knows which file type it is! Note that it’s shorter to include a stylesheet in your rhtml page this way!

For more information, read AssetTagHelper

In your layout template, you may want to include a variable(s) for appending stylesheets to your page.

For example you can have:


<=@content_for_page_stylesheets>

In you individual pages, you can then add individual stylesheets.

For example in index.rhtml:


<% content_for :page_stylesheets do >
<
=stylesheet_link_tag(’custom_stylesheet’)>
<
end %>

If you like, you can also create a directory structure for your stylesheets. Each page and template can have its own stylesheets. Something akin to the following would work:

public/stylesheets/controller_name/template_name.css

Comment:

You should also be aware that if you use the generator to generate scaffold code, it will also generate an app/public/stylesheets/scaffold.css that is automatically included in all the scaffold views.

Comment:

If you are going to print the page, be aware that the default for stylesheet_link_tag is :media =>"screen". I am not sure what makes more sense— :media=> “screen” or :media=>"all" — you should just be aware of this when you are trying to make a report for clients that prints out prettily. A quick perusal of several “Rails” sites made me think that no one has found this little gem.