Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Responsive hero image as CSS background image?

Tags:

css

For my responsive site I want to have a hero image as a background image not an image in the html.

I can make the div be 100% width easily, but im not sure how to make it have the correct height. I have to set a height in px but the height required depends on the div's width, which varies as the site is responsive.

<div class="cont">
  <p>Below is an image in the html that scales correctly</p> 
  <img src="http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg" />
  <p>The example below is a background image in CSS</p>
  <div class="hero-img"></div>
  <p>Some text</p>
</div>

.cont {
  width: 20%;
  margin: auto
}
img {
  max-width: 100%;
}

.hero-img {
  background: url("http://www.hdwallpapers.in/walls/abstract_color_background_picture_8016-wide.jpg") no-repeat;
  background-size: 100% 100%;
  height: 200px;
}

http://codepen.io/anon/pen/FBxkz

enter image description here

UPDATE - Background-size cover or contain do not fix my problem. The div with the image still has a fixed height.

http://codepen.io/anon/pen/FCafi

enter image description here

like image 873
Evanss Avatar asked May 09 '14 14:05

Evanss


2 Answers

Change background-size: 100% 100%; to background-size: cover;

More on background-size:cover from MDN

cover

This keyword specifies that the background image should be scaled to be as small as possible while ensuring both its dimensions are greater than or equal to the corresponding dimensions of the background positioning area.

nb. Per the comment from Terry below, you may also want to add background-position: center center; to ensure the image stays centred.

like image 162
SW4 Avatar answered Nov 14 '22 07:11

SW4


background-size: cover; will crop the image to ensure the entire div is covered by it. If you want to prevent cropping, you can use background-size: contain;.

The behaviour is similar, but using contain forces the background image to be scaled to ensure that its dimensions are smaller than or equal to the corresponding dimensions of the background positioning area.

like image 38
MarioDS Avatar answered Nov 14 '22 05:11

MarioDS