How to set a background image in rails from css?

2019-01-17 03:04发布

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.

11条回答
趁早两清
2楼-- · 2019-01-17 03:27

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

查看更多
我只想做你的唯一
3楼-- · 2019-01-17 03:29

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

body {
  background-image: image-url('texture.png'); // link to /assets/images/texture.png
}
查看更多
Fickle 薄情
4楼-- · 2019-01-17 03:35

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.

查看更多
时光不老,我们不散
5楼-- · 2019-01-17 03:36

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>
查看更多
祖国的老花朵
6楼-- · 2019-01-17 03:37

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.

查看更多
登录 后发表回答