Rails:如何从CSS中设置Rails的背景图像?

63

我正在使用Rails 3.2,需要为其中一个页面设置背景。我尝试了很多方法都没有成功,希望能得到一些好的帮助。

我已经尝试过:

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

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

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

什么都没用。请帮帮我。


惊讶于没有人花时间点赞,考虑到它已经被浏览了2236次。给我一个加分吧。 - RajG
2
background: url(<%= asset_path 'background.jpg' %>) 对我很有用 http://guides.rubyonrails.org/asset_pipeline.html#css-and-erb - kangkyu
14个回答

47
在您的 CSS 中:
background-image: url(background.jpg);

或者

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

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

你在哪里添加你的CSS文件? - Rajarshi Das
它位于assets/stylesheets/application.css文件中。 - logesh
我需要在application.rb或environments文件中设置任何内容吗? - logesh
好的...那么这是你的CSS问题,你检查过CSS中是否漏掉了分号以及使用CSS验证器来验证你的CSS,例如background-image: url(background.jpg); 或者 background-image: url(/assets/background.jpg); - Rajarshi Das
1
将CSS转换为SCSS可能会有所帮助,并在application.scss中使用@import。除此之外,将URL更改为asset-url、font-url即可,无需进行其他更改。 - Raj Kumar Goyal
显示剩余12条评论

30

对于Sass(SCSS)来说,以下代码适用于以下图像路径

app/assets/images/pictureTitle.png

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

你可能还需要重新启动你的Rails服务器。


11

如果您的图片在公共目录中,例如public/bg.jpg

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

如果您在app/assets/images目录下有一张名为bg.jpg的图片

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

似乎不起作用。如果我的图像在app/assets/images中怎么办? - logesh

5

这个问题有很多答案,我想分享我的解决方案,它解决了原始问题,因为他们最初尝试使用ERB helper之一:

按照上面Kangkyu的链接,我学到可以在我的.css文件上添加.erb文件扩展名。那绝对是Kangkyu所做的。

application.css.erb

这使我可以访问helper方法。

我不需要费心去弄清楚图片的正确路径,我使用了:

<%= asset_path "image_name.png" %>

所以我的CSS属性/值对看起来像这样:

background-image: url(<%= asset_path 'foo.jpg' %>);

3
如果您正在使用Sass(scss),请使用image-url函数:
body {
  background-image: image-url('texture.png'); // link to /assets/images/texture.png
}

先生,但它没有成功,您认为问题出在哪里? - Angel

3

这个问题可能比你想象的更深层次。它很可能不是Rails资源的问题,正如许多人所认为的那样,而是你的html元素之间的“沟通不畅”。原因如下:

  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)
希望这能帮到有需要的人。并且我发现,如果使用Bootstrap,要将背景图片覆盖在 nav 上并不那么容易;你的 nav 和其他元素都需要是同一个父元素(例如,上面所示的我的 header),此外,你还需要在你的 homepage.html.erb 以及每个其他页面中呈现导航栏,而不仅仅是在 application.html.erb 中呈现。 更新 好的,这就是我做的,以便展示完整的背景图片,不用在这里那里插入文本。在我的 application.scss 文件中,加入了 height 属性,就像这样:
     body {
background: url('pic-name.jpg') no-repeat center center;
background-size: cover;
height: 600px;}

注意:使用height: 100%无效。


2

我在开发一个Rails 6应用时遇到了这个问题。

以下是我的解决方法

如果一个图片位于app/assets/images/my-image.jpg,并且它是CSS背景图片,你需要这样引用它:

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

假设有一张图片位于app/assets/images/slides/my-slide.jpg,如果它是一个CSS背景图片,你应该这样引用:

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

注意: 这在开发和生产环境中都运行良好。

您可以在官方Rails文档中了解更多信息:链接到资源的编码方式


2

我按照上面的建议进行了操作(谢谢!)- 万一对其他人不起作用的话 - 这个解决方案对我有用:

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

因此,我必须在我的scss中使用“background”而不是“background-image”。


1

我为此苦苦挣扎了整整一天。最终,我通过在包含背景图的视图中编写CSS代码,在开发和生产环境都使它正常工作:

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

然后在表格本身上创建了一个id为tile的div,如下所示:

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

Ruby 2.3.7 Rails 5.2.0

0

好的,希望这能帮到某些人!最近我也遇到了类似的情况,想要在主题中实现一个图像。 只要你在app/assets/images文件夹中有一个名为blog_image.jpeg的图像,这个解决方案就适用于我的home_page_header.html.erb文件:

<!-- 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>

这在开发中对我起作用了,但在生产环境中却没有。我仍然没有弄清楚如何使其在生产环境中工作。 - tomb

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接