【问题标题】:HTML and CSS background-imageHTML 和 CSS 背景图像
【发布时间】:2014-07-06 15:43:07
【问题描述】:

我是一个我的 Rails 应用程序,我正在更改页面的 html 部分(localhost:3000/feeds),在文件 index.html.erb 中我以这种方式设置背景

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
  <html>

    <head>

      <style type="text/css">
          body
          {
            background-image:url("../../assets/images/wwi.jpg");
          }
        </style>

    </head>
</html>

目录是这样设置的:

->app
 ->assets
  ->images
    ->wwi.jpg
 ->views
  ->feeds
   ->index.html.erb

但是当我启动 rails 服务器并转到 localist:3000/feeds 时,没有背景(背景颜色没有问题)

【问题讨论】:

  • 你确定路径正确吗?

标签: html css ruby-on-rails image background


【解决方案1】:

您没有通过在视图中编写 css 来使用 rails 资产管道。如果您查看文档,它会说

Asset pipeline concatenate assets, which can reduce the number of requests that a browser makes to render a web page. Web browsers are limited in the number of requests that they can make in parallel, so fewer requests can mean faster loading for your application

*所以你应该使用它,首先从你的布局或视图中删除所有样式,你需要在你的布局文件中包含 rails application.css

<%= stylesheet_link_tag "application", media: "all" %>

此标签将使 Rails 使用在 assets/stylesheets/application.css 中查找您的样式。现在你需要使用你刚刚制作的 style.css.erb 来包含你的样式

*= require style 

现在在你的 style.css.erb 中你可以有这样的风格:

body{
  background-image: url(<%= asset_path 'wwi.png' %>)
}

更新:

如果您想改用 sass,那么您的文件将是 style.css.scss 并且可以使用 rails image-url 助手,因此您可以这样做: p>

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

更多详情请参考rails asset pipeline

【讨论】:

    【解决方案2】:

    使用资产管道时,路径应相对于根目录

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

    假定图像。

    你也可以使用资产助手

    &lt;%= asset_path 'wwi.png' %&gt;

    我建议你阅读资产管道的文档

    http://guides.rubyonrails.org/asset_pipeline.html

    【讨论】:

    • 第一个示例在生产模式下不起作用(文件名中添加了 md5 指纹)。应该推荐使用asset_path
    • 以及我在哪里以及如何使用
    猜你喜欢
    • 2013-03-13
    • 2012-02-08
    • 2015-05-06
    • 2019-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-13
    相关资源
    最近更新 更多