Ace Dimasuhid
Ace Dimasuhid

Reputation: 1062

How to get image url in css inside a public folder in Rails?

I have a css located inside the public/ folder in rails. I want to locate the images inside the app/assets/images/ folder for a background in the css. The code below doesn't seem to work:

background: url("bg-noise.png");

This is normally used for css inside the app/assets/stylesheets/ folder. Can't make it work inside the public folder.

Upvotes: 1

Views: 6425

Answers (4)

Simone Carletti
Simone Carletti

Reputation: 176562

You have two alternatives. If you can rename the file and use the asset pipeline with SCSS, then rename the style to .css.scss and replace

background: url("bg-noise.png");

with the image-url SCSS helper.

background: image-url("bg-noise.png");

It will automatically resolve the path.

Another solution is to rename the file to .css.erb and you'll be able to use ERB code inside the file.

background-image: url(<%= asset_path 'bg-noise.png' %>)

The last solution is to hard-code the path.

background: url("/assets/bg-noise.png");

I encourage you to use the first option.

Upvotes: 0

zolter
zolter

Reputation: 7160

background: url('/assets/bg-noise.png');

Upvotes: 0

Thaichor Seng
Thaichor Seng

Reputation: 105

if u inspect that element and expend the tab background: url(); and look for image background-image: url('localhost:3000/assets/bg-noise.png');

so in order to avoid that, use

{
background: url('../bg-noise.png');
}

Upvotes: 0

Kees Sonnema
Kees Sonnema

Reputation: 5784

You better use this to locate your images

background-image: url(<%= asset_path 'bg-noise.PNG' %>)

and if you have an images folder use:

background-image: url(<%= asset_path '/images/bg-noise.PNG' %>)

Upvotes: 2

Related Questions