Reputation: 16489
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
Upvotes: 3
Views: 7624
Reputation: 1133
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.
Upvotes: 2
Reputation: 20844
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).
Upvotes: 6