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
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With