66

I am using rails 3.2 and i have to set a background for one of the page and i have tried many ways and nothing went right, so looking for some good help. I have tried

background: url(<%= asset_path 'background.jpg' %>)

background: url("public/background.jpg");

background-image:url('/assets/images/background.jpg')

and nothing worked. Please help me.

3
  • surprised no one has taken time to up-vote this considering it has been viewed 2236 times. 1+ form me.
    – RajG
    Commented Dec 11, 2014 at 22:07
  • 2
    background: url(<%= asset_path 'background.jpg' %>) worked for me guides.rubyonrails.org/asset_pipeline.html#css-and-erb
    – kangkyu
    Commented Sep 13, 2017 at 12:50
  • @kangkyu, this is indeed the rails way answer for this question, thanks a lot! Commented Jun 14 at 19:47

14 Answers 14

47

In your CSS:

background-image: url(background.jpg);

or

background-image: url(/assets/background.jpg);

In environments/production.rb:

# Disable Rails's static asset server (Apache or nginx will already do this)  
config.serve_static_assets = false

# Compress JavaScripts and CSS  
config.assets.compress = true

# Don't fallback to assets pipeline if a precompiled asset is missed  
config.assets.compile = false

# Generate digests for assets URLs  
config.assets.digest = true
17
  • where you add your css files? Commented Aug 7, 2013 at 10:24
  • it is in assets/stylesheets/application.css
    – logesh
    Commented Aug 7, 2013 at 10:26
  • Do i have to set any thing in application.rb or in environments file?
    – logesh
    Commented Aug 7, 2013 at 10:28
  • If your images are in public images folder? please put it in assets images folder Commented Aug 7, 2013 at 10:28
  • 1
    Convert css to scss may help and use @import in application.scss Other than this, change url to asset-url, font-url Except these nothing needs to change. Commented Feb 21, 2021 at 10:49
30

For sass (scss) this code works with the following image path

app/assets/images/pictureTitle.png

body { 
  background-image: image-url('pictureTitle.png'); 
}

You might also need to restart your rails server.

1
  • ChatGPT: La función image-url es una función proporcionada por Sass, específicamente diseñada para trabajar con el asset pipeline de Rails. No es una función estándar de CSS, sino una característica de Sass que ayuda a gestionar las rutas de los assets en Rails. Commented Jul 17 at 12:11
11

If you have the image in your public directory like public/bg.jpg

background-image: url('/bg.jpg')

If you have image in app/assets/images/bg.jpg

 background-image: url('/assets/bg.jpg')
1
  • Doesn't seem to work. What in case i have my image in app/assets/images?
    – logesh
    Commented Aug 7, 2013 at 10:26
6

Add the .erb extension to your target css file:

application.css.erb

This gives access to the helper methods.

<%= asset_data_uri "background.jpg" %>

Now you can use:

background-image: url(<%= asset_data_uri 'background.jpg' %>);
3

If you are using sass (scss), use image-url function:

body {
  background-image: image-url('texture.png'); // link to /assets/images/texture.png
}
1
  • But sir it didn't, what do you think the problem sir?
    – Angel
    Commented Apr 11, 2017 at 15:40
3

The problem could be more deeply ingrained than you think. It most likely is not a Rails asset problem as many presume, but 'miscommunication' between your html elements. Here's why:

  1. First of all, fool proof your code by puting the backgound image in the body element.

    body {
    background: url('pic-name.jpg') no-repeat center center;
    background-size: cover;}  /* For a full size background image */
    
  2. Then check your developer tools console to see if the image is getting loaded correctly or it's giving a 404 not found.
  3. If giving a 404, then your css syntax is not correct, try any other of this post's answers until you no longer get a 404. For me the above example worked:
  4. Once you realize that the console doesn't give a 404 anymore, confirm the image actually loads with this:

    http://localhost:3000/assets/pic-name.jpg

    • I understand that this could vary per individual, but try it and make sure you've used your pic's name.
  5. If it loads well, now you know the culprit - the body element is hiding something - when you put the image in the body, it works, when you put it in another element, it works not.
  6. This is the trick; in that other element where you want the background image, mine was header, insert some text or some lines, Yes, just plain text or something! Mine was:

    <header>
       <%= render 'shared/navbar' %> # To have the nav's backgrond as the image
       <div class="container">
          <div class="text-center">
            <h2><strong>Nairobi</strong></h2> <hr>
            <h2><strong>Is</strong></h2> <hr>
            <h2><strong>Just a Beula Land</strong></h2> <hr>
          </div>
      </div>
    

  7. And alas, it worked! Though it didn't show the full image, just the upper part. But at least I knew it worked.

  8. And if you add more text, the image stretches downwards (more gets shown)

Hope this helps someone. And along with this I realised that it was not that easy to place the background image to cover the nav as well, esp if using bootstrap; both the nav and your other element need to be children of the same parent element, eg, mine was the header as shown above, and you'll also have to render the nav inside your, say, homepage.html.erb, and every other page, as opposed to just rendering it on the application.html.erb

Update

Okay, this is what I did to show the full background image without inserting texts here and there. In my application.scss, where you have your css, I simply added the height property, like so

     body {
background: url('pic-name.jpg') no-repeat center center;
background-size: cover;
height: 600px;}

N.B: Using height: 100% didn't work.

2

I followed the suggestions above (Thank you!) - just in case it doesn't work for others either - this solution worked for me:

.myClass {
   background: image-url('myPicture.png');
}

so instead of "background-image" I had to use "background" in my scss.

2

I had this challenge when working on a rails 6 application.

Here's how I fixed it:

For an image located in app/assets/images/my-image.jpg, assuming that it is a CSS background image, you should reference this way:

background-image: url(<%= /assets/my-image.jpg' %>)

For an image located in app/assets/images/slides/my-slide.jpg, assuming that it is a CSS background image, you should reference this way:

background-image: url(<%= asset_path 'slides/my-slide.jpg' %>)

Note: This worked well in development and production environments

You can read up more on this in the official Rails Documentation: Coding Links to Assets

1

I struggled with this for an entire day. Finally I got it working in both development and production by coding the css in the view that holds the background image:

<head>
    <style>
        #tile {
            background: url(<%= asset_path 'background.jpg' %>);
            background-size: cover;
            }
    </style>        
</head>

Then on the sheet itself I created a div with id=tile like this:

<div id=tile>
  <div class=row>
  ...added more stuff
  </div>
</div>

Ruby 2.3.7 Rails 5.2.0

0

Ok, hope this helps someone!! I was in a similar situation recently looking to implement an image for a theme. This solution worked for me in a home_page_header.html.erb file provided that you have an image called blog_image.jpeg in your app/assets/images folder:

<!-- Page Header -->
<header class='masthead' style='background-image: url(assets/blog_image.jpeg)'>
  <div class='container'>
    <div class='row'>
      <div class='col-lg-8 col-md-10 mx-auto'>
        <div class='site-heading'>
          <h1>Omega</h1>
          <span class='subheading'>Sample text</span>
        </div>
      </div>
    </div>
  </div>
</header>
1
  • This worked for me in development, but not production. Still haven't figured out how to make it work in production.
    – tomb
    Commented Aug 30, 2018 at 1:36
0

[CONTEXT] Ruby 2.6.3 | Rails 6.0.1 | Using webpack to bundle stylesheets.

I realized I couldn't deliver images from the asset pipeline in [s]css from webpack files: for instance, Asset Helpers from sass-rails are unavailable.

After some struggle, I found the solution on https://stackoverflow.com/a/57175231/8131629

-1

Try the code below:

.background-style {
    background-image: url("../images/background.jpg");
}
-2

if you have your image into app/assets/images and its name is 'zi-fullscreen-bg.png', for example then you can use

.hero-unit.fullscreen-image-bg {
  background-image: url('zi-fullscreen-bg.png');
}

at least it worked for me!

-2

It seems that double quotes work.

Here is my example:

body {
  background-image: url("sunset");
}

And the sunset jpeg is located in my assets folder.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.