Serving images via CSS in Rails

Ruby on Rails is versatile enough to help you access and service image from your css files. It relies on Rails Asset Pipeline helpers.

You can reference your images within CSS files via two helpers

1. image-url("my-image.jpg")

2. image-path("my-image.jpg") 

Both of these helpers will convert your image reference path to /assets/my-image.jpg. There is also generic way of accessing images or other file types in Rails. 

3. asset-url("my-image.jpg")

4. asset-path("my-image.jpg") 

All four ways of accessing images from within CSS file are acceptable in Rails 4 application.

Finally, here is full CSS set up for your example

background-image: image-url("my-background-image.jpg")

Featured pages

Ruby

Set of Ruby Object Oriented Programming Language tutorials that cover such topics as Ruby strings, …

Rails

Rails Framework tutorial teaches you how to utilize de facto framework of choice for Ruby developme…

Ruby Duck Typing

“If an object quacks like a duck just go ahead and treat it as a duck” – this fun…

Regular Expressions

Ruby uses the =~ operator to check any given string against regular expression. For example, a stri…

Credit Card Number

Every last digit of any credit card is a check sum digit that is determined by all digits in front …

Ruby Arrays

Ruby Programming Language has built in support for Arrays. Arrays help you define some of the compl…

Ruby Hashes

Hashes are very similar to arrays in Ruby and hashes interface is similar to Ruby array interface. …

Ruby Code Block

Ruby is very unique language when it comes to code blocks. You can simply pass a code block to a me…