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

3
  • Shouldn't the background url path be /assets/images/header-bg.jpg Commented Nov 13, 2014 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 Commented Nov 13, 2014 at 22:05
  • Take a look Here then Commented Nov 13, 2014 at 22:12

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

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
You have to use percentage(%) instead of fixed value (px).
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.