简体   繁体   中英

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.

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. This also adds a cache-busting fragment to the url which avoids issues with stale cached assets.

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.

You can do this in two ways:

1. ERB (Embedded Ruby)

Change the extension of the file to .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. This is very much the same as using ERB to create HTML in your views.

2. SASS-Rails

Make sure you have the sass-rails gem installed and change the file extension name to .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. The SASS compiler then inserts the correct url when the stylesheet is compiled.

玛库确保您在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

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');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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