Evans Evans - 9 months ago 57
CSS Question

Responsive hero image as CSS background image?

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>

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


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.


enter image description here

Answer Source

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

More on background-size:cover from MDN


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.