allegutta
allegutta

Reputation: 5644

Rails: Load image from CSS

In my view I can load a image with this line of code: <div id="bglion"><%= image_tag("BG-LION6.png")%></div> (this works), but instead I want to load the image from the CSS file.

After reading arround, I have tried this:

#bglion {src: background:url('BG-LION6.png');}
#bglion {src: asset-url('BG-LION6.png');}
#bglion {src: asset-url('BG-LION6.png', image);}

...but the picture won't load on the page. How can I make it work?

(The image is in /assets/images)

Upvotes: 2

Views: 3863

Answers (3)

Matthew Hui
Matthew Hui

Reputation: 3361

You can change your css file to have a css.erb extension and then do something like this

#bglion {
background-image: url(<%=asset_path "BG-LION6.png"%>);
}

Upvotes: 1

Tracy Fu
Tracy Fu

Reputation: 1662

I think you'll have to do a couple of things. Your CSS should probably be something more along the lines of this:

#bglion { background: image-url('BG-LION6.PNG'); }

background is the CSS property you're actually trying to set. src is not a CSS property. image-url is a Rails path helper that points to your image assets folder. I believe if you just use asset-url it points to your entire assets folder and you would still have to specify that your image is in the images folder.

Secondly, if your div no longer contains an image within it, it will collapse to a width and height of 0 cause there's nothing to define its dimensions. You'll have to add more CSS to the wrapper div to define the dimensions of the image. So something like this:

#bglion { background: image-url('BG-LION6.PNG'); width: 100px; height: 100px; }

Upvotes: 4

Moox
Moox

Reputation: 1117

Try to do this instead:

#bglion { background: url("/BG-LION6.png"); }

or

#bglion { background: url("/assets/BG-LION6.png"); }

Depending on which version of rails you're using and which folder you set your assets at.

When accessing assets, you should always make the path absolute instead of relative.

Upvotes: 3

Related Questions