简体   繁体   中英

How to set a background image on a Rails app using CSS

I'm building a rails app and trying to set a background image for the welcome page. For some reason the image won't show and I'm not sure why. I've looked at numerous questions on here but I'm still unable to resolve.

Here's my latest code -

welcome.css.scss

body {
  background: url('/assets/mamaknowscollage.jpg');
}

I've also tried (amongst numerous other variations) -

body {
  background-image:  url('/assets/mamaknowscollage.jpg');
}

Here's the html (the image tag here is for the logo)

welcome.html.erb -

<header>


</header>
<body>


            <image><%= link_to image_tag('MamaKnowsLogo.jpg'), root_path, id: "logo" %></image>

</body>

I've left the url path as is but I've also tried it without assets and it still doesn't work.

Any ideas what I'm doing wrong?

如果文件位于assets/images文件夹中,请按照以下步骤进行操作

 background: image-url('mamaknowscollage.jpg');

You could rename your welcome.css.scss file to welcome.scss.erb and try it out. (SCSS will work!)

Write the path as

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

The image file should be placed in assets/images.

Source: Rails Guide

  • Firstly, rename your file to welcome.scss.erb .
  • Then make sure to include your welcome.scss.erb into application.css.erb .

Simply add the line:

*= require welcome
  • Then you should check if it works - for example, try setting the background to blue .
  • Lastly, it should be simple to figure out the correct path to your image.

With scss , you can do it as follow:

body {
 background:url(asset-path('mamaknowscollage.jpg')) 0px 0px;
}

The mamaknowscollage.jpg file should be placed in assets/images

About this problem, i think you should remove image tag.

<body>
  <%= link_to image_tag('MamaKnowsLogo.jpg'), root_path, id: "logo" %>
</body>

First rename your css file welcome.css to welcome.scss and application.css to application.scss

in application.scss file add @import 'welcome'

If your images are in app/assets/images folder then use:

background: image-url("my_image.jpg");

If your images are in app/assets/images/SomeFolder folder then use:

background: image-url("SomeFolder/my_image.jpg");

After much tinkering, I fixed the issue by adding a "class" to the body element on the welcome.html.erb file and applying the appropriate css code -

 body.background {
     background: url('mamaknowscollage.jpg');

  }

HTML -

 <body class="background">

     <div class="welcome">



         <%= image_tag('MamaKnowsLogo.jpg') %>

     </div>

 </body>

Thanks to all who made contributions.

body {
  background-image: url(mamaknowscollage.jpg);
}

worked for me!

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