dobsoft dobsoft - 2 years ago 223
HTML Question

Using a background image for one page in rails 4 app?

I am trying to give one of my views a background image. I have found info for rails three on how to do this, but it does not seem to work for me. Here is the link to the info I used:

Here is my welcome.css.scss:

.container {
background-image: url(images/image.jpg)


here is welcome/home.html.erb:

<html xmlns="" xml:lang="<%= I18n.locale || 'en' %>"

lang="<%= I18n.locale || 'en'%>">
<body class="container">



Answer Source

Firstly, you won't need to determine a class for the body tag - just call body in your CSS (and override for the specific page you want the background image on)

Secondly, you need to use asset_path helpers:

    image: asset-url("image.jpg")

This is the "correct" way to call this, as if you use .erb or any other other methods with the asset pipeline, you run the risk of losing your functionality when you precompile the assets for production

The trick is to use the rails asset preprocessors to allow the use of dynamic paths for your assets. The paths will be used depending on whether you're using your assets dynamically, or statically (in production)

Considering you have image.jpg in your /assets/images folder, the above code should work for you. The SCSS version would be:

  background: {
    image: asset-url("image.jpg");



You can call the welcome css like this:

   <%= stylesheet_link_tag "welcome" if controller_name == "welcome" %>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download