How do I know how many pixels a div has height:100%? And how can I subtract a certain value from that total of pixels and apply what’s left to another div

Asked

Viewed 345 times

0

I don’t know for sure how to do this, but in my case I would like to subtract 80 pixels from a div that has height:100%.

I saw that it has to take the height of a div, but I would like to do something that I believe is more complex!

As already says the question "how to know how many pixels has a div with height:100%? And how can I subtract a certain value from that total of pixels and apply what’s left to another div".

That is, I want that at the beginning of the page load some code take convert the 100% height of the div A in pixels. Ex: 100% = 500 pixels, of those 500 pixels I would like to subtract any value, in my case 80 pixels, so that leaves a total of 420 pixels, and I would like these 420 pixels to be applied to another div. Is that possible? If so, how?

  • 1

    Edited answer because there was a small error.

1 answer

1


By using pure javascript, which can give you better performance, just use the clientHeight function to pick the height of the div in pixels then apply the other div the subtraction result:

window.onload = function () {
    var altura = document.getElementById('geral').clientHeight;
    alert(altura);
    var alturaDaOutraDiv = parseInt(altura) - 80;
    if(alturaDaOutraDiv > 0){
        document.getElementById('outra').style.height= alturaDaOutraDiv+"px";
        var alturaDaOutra = document.getElementById('outra').clientHeight;
        alert(alturaDaOutra);
    }
};
<div id="geral">
    Oi eu sou uma div com conteudo html.
    <p>Oi</p>
    <p>Oi</p>
    <p>Oi</p>
    <p>Oi</p>
    <p>Oi</p>
    <p>Oi</p>
    <p>Oi</p>
    
</div>
<div id="outra">
    conteudo da outra div
</div>

Testing: http://jsfiddle.net/ysz4a1wr/3/

  • It really works. But I only work on jsfiddle on localhost!

  • 1

    @Ivanveloso you must use window.onload or with jquery $(document).ready - I edited the test response on your localhost

  • Now it worked @Guilhermenascimento, thanks

Browser other questions tagged

You are not signed in. Login or sign up in order to post.