Surya Matadewa
Surya Matadewa

Reputation: 1027

Responsive height for div element

I have this code for a responsive banner

.mybanner { 
     height:320px; 
     background:url(../img/banner.png) no-repeat;  
     background-size:100%;
}

responsive image background works fine, the only problem is .mybanner container's height is not changing

for example when i test with big screen

mybanner div element width = 980px
mybanner div element height = 320px
bakcground_image width = 980px
background_image height = 320px    

but when i resized screen, let say width mybanner div element become 680px

mybanner div element width = 680px
mybanner div element height = 320px
bakcground_image width = 680px
background_image height = 220px    

from that example there is different value mybannder height with background_image height, so it's become ugly white space

I already tried to modify it like this, to make .mybanner height became auto

 .mybanner { 
     min-height:170px;
     max-height:320px; 
     background:url(../img/banner.png) no-repeat;  
     background-size:100%;
}

or this:

.mybanner { 
     height:100%; 
     //height:auto;
     background:url(../img/banner.png) no-repeat;  
     background-size:100%;
}

but not work....
any idea how to make height of div .mybanner change too depending on image size on his background

Upvotes: 0

Views: 99

Answers (1)

Martin
Martin

Reputation: 2673

You can use javascript to change height.

<body onresize="resizediv()">
<div class="mybanner" id="mybanner">
...

<script>
function resizediv() {
div = document.getElementById('mybanner');
    var imageSrc = div.style.backgroundImage.replace(/url\((['"])?(.*?)\1\)/gi, '$2').split(',')[0];

    var image = new Image();
    image.src = imageSrc;

    var width = image.width,
        height = image.height;

    div.style.height = image.height; 

}
</script>

Or There are all background size valid properties, you can chose best one:

http://www.w3schools.com/cssref/playit.asp?filename=playcss_background-size&preval=contain

Or simple don't use background, put the IMG to the div as a object and set image width 100% don't edit div and image height, it will compute automatically.

Upvotes: 1

Related Questions