简体   繁体   English

背景图像 css 在 rails 应用程序中不起作用

[英]background image css not working in rails app

Am using the background-image property in my rails app, i have used it previously, it's pretty easy and it works all the time but don't know why it's not working now.在我的 rails 应用程序中使用 background-image 属性,我以前使用过它,它非常简单并且一直有效,但不知道为什么它现在不起作用。

body{
    padding: 0;
    margin: 0;
    background-image: url("../assets/mainbanner.jpg");
    background-attachment:fixed;
    background-size:cover;
    font-family: 'Lato', sans-serif;
    display:block;
}

The Rails way is by using the Rails assets helpers to get the correct path to assets. Rails 的方法是使用Rails 资产助手来获取资产的正确路径。 This also adds a cache-busting fragment to the url which avoids issues with stale cached assets.这还会向 url 添加一个缓存破坏片段,以避免陈旧的缓存资产出现问题。

It also lets you for example later switch to Content delivery network (CDN) for assets without having to to deal with hardcoded paths in your CSS/JS and views.例如,它还允许您稍后为资产切换到内容交付网络 (CDN),而无需处理 CSS/JS 和视图中的硬编码路径。

You can do this in two ways:您可以通过两种方式执行此操作:

1. ERB (Embedded Ruby) 1.ERB(嵌入式Ruby)

Change the extension of the file to .css.erb将文件的扩展名更改为.css.erb

body {
    padding: 0;
    margin: 0;
    background-image: url("<%= asset_path('mainbanner.jpg') %>");
    background-attachment: fixed;
    background-size: cover;
    font-family: 'Lato', sans-serif;
    display: block;
}

Using the extension .erb causes the file to be sent through the ERB interpreter.使用扩展名.erb会导致文件通过 ERB 解释器发送。 This is very much the same as using ERB to create HTML in your views.这与使用 ERB 在视图中创建 HTML 非常相似。

2. SASS-Rails 2. SASS-Rails

Make sure you have the sass-rails gem installed and change the file extension name to .scss .确保安装了sass-rails gem 并将文件扩展名更改为.scss

body {
    padding: 0;
    margin: 0;
    background-image: url(asset_path('mainbanner.jpg'));
    background-attachment: fixed;
    background-size: cover;
    font-family: 'Lato', sans-serif;
    display: block;
}

SASS rails maps the Rails assets helpers to SASS functions. SASS rails 将 Rails 资产助手映射到 SASS 函数。 The SASS compiler then inserts the correct url when the stylesheet is compiled. SASS 编译器然后在编译样式表时插入正确的 url。

玛库确保您在assets文件夹中具有此background.jpg。请尝试此代码

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

 background-image: url('~images/shared/sign-page1.jpg');

使用公共图像为我工作

Change your .css file to .scss and try this将您的 .css 文件更改为 .scss 并尝试此操作

body{
    padding: 0;
    margin: 0;
    background-image: url(asset_path('mainbanner.jpg'));
    background-attachment:fixed;
    background-size:cover;
    font-family: 'Lato', sans-serif;
    display:block;
}

你可以这样做:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM