How do I reference a font or an image from my CSS files?

Rails uses a thing called the “asset pipeline” to pre-process your assets (Javascript, CSS, images and fonts).

This has a number of advantages – Javascript get minified and squashed into a single file for faster transmission, and the same happens to your CSS as well. All your static assets (the single JS file, the single CSS file, all your images and fonts) get marked with a timestamp so if you set a cache header, your browser knows to cache that file for evermore (and if you change it on a subsequent version the timestamp changes so the browser knows it’s a different file). And it also means you can work in SASS and Coffeescript instead of pure CSS and Javascript (and other preprocessors are available if you prefer as well).

But it does lead to some confusion.

If you stick a font into /app/assets/fonts how can you reference it in your CSS file?

Same goes for an image – after pre-processing where do they live?

Well, Rails offers you some helper methods to handle that for you.

Change your CSS to this:

and Rails will figure it out for you. And for images, you can use image_path too.

Do you know what to do but not how it works?

Ever wanted to understand why Rails views work the way that they do? Why variables from your controllers are visible inside your views?

Sign up below to get a free 5 part email course on how Ruby on Rails view rendering works and gain a deep understanding of the Rails magic.

We will send you the course, plus the occasional update from this web-site. But no spam, we promise, and it's easy to unsubscribe