Mark Wilson Mark Wilson - 29 days ago 4
CSS Question

Set Background image width 100% height auto

I have a banner section as such:



.bannerImage {
width: 100%;
height: auto;
}

<img src="http://www.w3schools.com/css/trolltunga.jpg" alt="banner image" class="bannerImage" />





So instead of using background image, I am using an image with
width
100%
and
height
auto
.

Now I want to add a banner title over the banner section. So, since it is not possible to achieve the effect with just image, I am using
background-image
property now. But with background image I want the same layout like how it was with just image. The background should always take width 100% and height should be auto. Below is my approach. As you can see the section adjusts to height of content. Is it possible to set it's height to image's height.



.bg_banner_image {
background-size: 100% auto;
background-position: center top;
background-repeat: no-repeat;
}

<div class="bg_banner_image" style="background-image: url('http://www.w3schools.com/css/trolltunga.jpg')">some content here</div>




Answer

Add the image within it and make it hidden (By using opacity:0;). so that it will fit

.bg_banner_image {
    background-size: 100% auto;
    background-position: center top;
    background-repeat: no-repeat;
}
.bannerImage {
    width: 100%;
    height: auto;
    opacity:0;
}
<div class="bg_banner_image" style="background-image: url('http://www.w3schools.com/css/trolltunga.jpg')">
<img src="http://www.w3schools.com/css/trolltunga.jpg" alt="banner image" class="bannerImage" />
</div>