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

Tags: css,ruby-on-rails

Problem :

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.

Solution :

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.

    CSS Howto..

    How to simplify CSS code

    How to convert a xml element into url using css?

    How to get only the last ul of specific id on page via CSS :last-child property?

    How to vertically align absolutely positioned images on top of one another?

    How to divide a border into 4 equal parts?

    how to display nav elements below each other inside of a header element

    How to style focused and visited anchors when scrolling with CSS / jQuery

    How can I set first element to display: none;?

    How to add css class?

    How do you maintain CSS layout when adding content (ASP.NET)

    How to make jQuery css affect upcoming elements

    How to fix this cell in the GridView?

    How to call a jquery funcion with a css button?

    jQuery, CSS: Two divs, how can I make them “show”next to each other?

    how to make menu on mouse hover in CSS

    Issue with changing how containers look based on values in an MD array

    How to link after the CSS-Animation?

    How to make a TableLayoutPanel like resizable div in html

    How to Change Default Bootstrap Fluid Grid 12 Column Gutter Width

    How to align text next to an icon with CSS?

    How to reference / link to a Css-File styling elements in a webview for Android

    How can I display a list in an x by y fashion?

    How to make space visible in between an unsorted list in HTML/CSS?

    How to keep css content position when zooming in and out?

    How to adjust the height of the footer automatically

    How to center icons in div consistently? [duplicate]

    How to reference css and script files into a node.js app?

    How to use box shadow in css?

    How to add a CSS table next to my google map?

    Fixed Header Scrollable Table - How to preserve horizontal scroll position using css jquery on page loads