3

How do I include a background image in Rails 4? I am trying to add it onto a div I have in my HTML. Currently, the image is in my /assets/images directory.

HTML:

<header>
  <div class="background_image">

  </div>
</header>

CSS:

.background_image {
    background: url(/assets/header-bg.jpg);
}

With the code I currently have, no images are being displayed

Substantial
  • 6,684
  • 2
  • 31
  • 40
Liondancer
  • 15,721
  • 51
  • 149
  • 255
  • Shouldn't the background url path be `/assets/images/header-bg.jpg` – Bijan Nov 13 '14 at 22:04
  • @Bijan well i think without rails 4 yes but I am reading around and it seems to me rails does some preprocessing that doesn't require the `images` portion – Liondancer Nov 13 '14 at 22:05
  • Take a look [Here](http://stackoverflow.com/questions/15257555/how-to-reference-images-in-css-within-rails-4) then – Bijan Nov 13 '14 at 22:12

2 Answers2

6

Firstly, you need to add to your CSS file SCSS extension, like main.css.scss.

With that you can use the asset helpers, like:

.background_image {
    background: image-url('header-bg.jpg');
}

As is stated in the docs, image-url("header-bg.jpg") becomes "url(/assets/header-bg.jpg)".

Your markup is currently empty (div.background_image) so you'll need to add some height to the style to make it work.

<header>
    <div class="background_image">
        <!-- no content -->
        <!-- add some content or specify some height -->
    </div>
  </header>

Note: to make all of this work, you must use the sass-rails gem (it's default in rails 4).

Vucko
  • 20,555
  • 10
  • 56
  • 107
  • Apparently the image has been appearing within the browser but it is incredible small (think thin line) so it appeared it wasnt there. However, adding properties such as `height:600px;` displays the image. Not sure what to do to correctly display this image as I stretch the browser. I need content in my CSS to scale the image with the browser inside of maintaining a static size – Liondancer Nov 13 '14 at 23:01
  • You have to use percentage(`%`) instead of fixed value (`px)`. – Vucko Nov 14 '14 at 06:15
2

This is an old post but I feel this could still use a better answer. Resizing the image is tricky in bootstrap so getting it to adjust or appear as you want it will require some photoshoping but the code to get it where you want it might look as follows as this should cover you across almost all browsers:

background: url('header-b.jpg');
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: 100%;

Additionally you can add some more css to your background depending on how large the image and or space is like so:

background: url('header-b.jpg') no-repeat center center;

Adding fixed to that will lock your image in place but can be used.

Juan Pablo Ugas
  • 1,085
  • 9
  • 22