CSS 如何从css在rails中设置背景图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18100650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:51:59  来源:igfitidea点击:

How to set a background image in rails from css?

cssruby-on-railsruby-on-rails-3ruby-on-rails-3.2background-image

提问by logesh

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

我正在使用 rails 3.2,我必须为其中一个页面设置背景,我尝试了很多方法,但没有任何效果,所以寻找一些好的帮助。我试过了

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

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

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

and nothing worked. Please help me.

没有任何效果。请帮我。

采纳答案by Rajarshi Das

In your CSS:

在你的 CSS 中:

background-image: url(background.jpg);

or

或者

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

In environments/production.rb:

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

回答by ernbrn

For sass (scss) this code works with the following image path

对于 sass (scss),此代码适用于以下图像路径

app/assets/images/pictureTitle.png

应用程序/资产/图像/pictureTitle.png

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

You might also need to restart your rails server.

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

回答by Bachan Smruty

If you have the image in your public directory like public/bg.jpg

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

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

If you have image in app/assets/images/bg.jpg

如果你在 app/assets/images/bg.jpg 中有图片

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

回答by Ruto Collins

The problem could be more deeply ingrained than you think. It most likely is not a Rails asset problem as many presume, but 'miscommunication'between your html elements. Here's why:

这个问题可能比你想象的更根深蒂固。它很可能不是许多人认为的 Rails 资产问题,而是html 元素之间的“误传”。原因如下:

  1. First of all, fool proof your code by puting the backgound image in the bodyelement.

    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 bodyelement 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 otherelement 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)
  1. 首先,通过将背景图像放在body元素中来证明您的代码。

    body {
    background: url('pic-name.jpg') no-repeat center center;
    background-size: cover;}  /* For a full size background image */
    
  2. 然后检查您的开发人员工具控制台以查看图像是否正确加载或未找到 404。
  3. 如果给出 404,那么您的 css 语法不正确,请尝试本文中的任何其他答案,直到您不再得到 404。对我来说,上面的示例有效:
  4. 一旦您意识到控制台不再提供 404,请确认图像实际加载如下:

    http://localhost:3000/assets/pic-name.jpg

    • 我知道这可能因人而异,但请尝试并确保您使用了照片的名称。
  5. 如果它加载良好,现在您知道罪魁祸首 -body元素隐藏了某些东西 - 当您将图像body放入 .
  6. 这就是诀窍;在other你想要背景图像的那个元素中,我的是header,插入一些文本或一些行,是的,只是纯文本或其他东西!我的是:

    <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. 唉,它奏效了!虽然它没有显示完整的图像,但只显示了上半部分。但至少我知道它有效。

  8. 如果添加更多文本,图像会向下延伸(显示更多)

Hope this helps someone. And along with this I realised that it was not that easy to place the background image to cover the navas well, esp if using bootstrap; both the navand your other element need to be childrenof the same parent element, eg, mine was the headeras shown above, and you'll also have to render the nav inside your, say, homepage.html.erb, and every other page, as opposed to just rendering it on the application.html.erb

希望这可以帮助某人。与此同时,我意识到放置背景图像来覆盖也不是那么容易nav,尤其是如果使用引导程序;无论是nav和您的其他元素需要是children相同的parent element,例如,我的是header如上图所示,你还必须使你的,比方说,里面的导航homepage.html.erb,以及所有其他网页,而不是仅仅使其上这application.html.erb

Update

更新

Okay, this is what I did to show the full background image without inserting texts here and there. In my application.scss, where you have your css, I simply added the height property, like so

好的,这就是我为显示完整的背景图像所做的,而不是在这里和那里插入文本。在我application.scss的 css 文件中,我简单地添加了 height 属性,如下所示

     body {
background: url('pic-name.jpg') no-repeat center center;
background-size: cover;
height: 600px;}

N.B: Using height: 100%didn't work.

注意:使用height: 100%不起作用。

回答by Georg Keferb?ck

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.

所以我不得不在我的 scss 中使用“背景”而不是“背景图像”。

回答by atomAltera

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

如果您使用 sass (scss),请使用 image-url 函数:

body {
  background-image: image-url('texture.png'); // link to /assets/images/texture.png
}

回答by J.R. Bob Dobbs

Lots of answers for this one, figured I'd throw in my solution, which addresses the original question, since they were originally attempting to use, among other things, an ERB helper:

这个答案有很多,我想我会提出解决原始问题的解决方案,因为他们最初试图使用 ERB 助手等:

following the link from above from Kangkyu, I learned it's possible to add the .erb file extension onto my .css file. Which is definitely what Kangkyu did.

按照上面来自 Kangkyu链接,我了解到可以将 .erb 文件扩展名添加到我的 .css 文件中。这绝对是康奎所做的。

application.css.erb

应用程序.css.erb

This gives me access to the helper methods.

这使我可以访问辅助方法。

Instead of fussing with figuring out the correct path to the image, I used:

我没有大惊小怪地找出图像的正确路径,而是使用了:

<%= asset_path "image_name.png" %>

so my CSS property/value pair looks like this:

所以我的 CSS 属性/值对如下所示:

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

回答by tomb

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:

我为此挣扎了整整一天。最后,我通过在包含背景图像的视图中编码 css 使其在开发和生产中都能正常工作:

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

然后在工作表本身上,我创建了一个 id=tile 的 div,如下所示:

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

Ruby 2.3.7 Rails 5.2.0

红宝石 2.3.7 导轨 5.2.0

回答by Max Press

[CONTEXT] Ruby 2.6.3 | Rails 6.0.1 | Using webpack to bundle stylesheets.

[上下文] Ruby 2.6.3 | Rails 6.0.1 | 使用 webpack 捆绑样式表。

I realized I couldn't deliver images from the asset pipeline in [s]css from webpack files: for instance, Asset Helpers from sass-rails are unavailable.

我意识到我无法从 webpack 文件的 [s]css 中的资产管道传递图像:例如,来自 sass-rails 的资产助手不可用。

After some struggle, I found the solution on https://stackoverflow.com/a/57175231/8131629

经过一番挣扎,我在https://stackoverflow.com/a/57175231/8131629上找到了解决方案

回答by TheMissingNTLDR

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:

好的,希望这对某人有所帮助!!我最近遇到了类似的情况,希望为主题实现图像。这个解决方案在 home_page_header.html.erb 文件中对我有用,前提是您的 app/assets/images 文件夹中有一个名为 blog_image.jpeg 的图像:

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