0

Is there a way to measure height of a div element using javascript?

Here is my situation: I created a top fixed position bar on my website, so even if I scroll the page up/down, the bar stays on top, but my problem is bar overlaying the webpage, what I want is bar pushing the webpage down for the height of the bar so they look like stacked, I managed to do it by fixed height, say 50ox, I set html page top margin and they looked ok, when the height of bar changes, for example looking the same page in mobiles goes wrong because height of bar increases in mobile but the top margin I set is still 50, so I need a way to measure actual height of bar when ti is rendered and adjust the page according to it.

Raavan INR
  • 19
  • 4

1 Answers1

1

If you fix the top bar in position, you shouldn't have to worry about the contents below it actually showing below it unless you've modified their positions as well. If that's the case then you can calculate the height of an element using window.getComputedStyle() and you can use that value to set the margin.

var wrapper = document.getElementById("wrapper");
var banner = document.getElementById("banner");
var content = document.getElementById("content");

var bannerHeight = window.getComputedStyle(banner).height;

console.log("Height of the banner is: " + bannerHeight);

content.style.marginTop = bannerHeight;
#wrapper { background: #e0e0e0; }
#banner { background: #ff0; position:fixed; top:0; width:100%; z-index:99; }
#content { background: #66f; position:relative;  }
<div id="wrapper">
  
  <div id="banner">
    <h1>This is the page banner</h1>
  </div>
  <div id="content">
    <h1>This is FIRST LINE of the main content area of the document.</h1>
    <p>This is the main content area of the document.</p>
    <p>This is the main content area of the document.</p>
    <p>This is the main content area of the document.</p>    
    <p>This is the main content area of the document.</p> 
    <p>This is the main content area of the document.</p>
    <p>This is the main content area of the document.</p>
    <p>This is the main content area of the document.</p>
    <p>This is the main content area of the document.</p>    
    <p>This is the main content area of the document.</p> 
    <p>This is the main content area of the document.</p>
    <p>This is the main content area of the document.</p>
    <p>This is the main content area of the document.</p>
    <p>This is the main content area of the document.</p>    
    <p>This is the main content area of the document.</p> 
    <p>This is the main content area of the document.</p>
    <p>This is the main content area of the document.</p>
    <p>This is the main content area of the document.</p>
    <p>This is the main content area of the document.</p>    
    <p>This is the main content area of the document.</p>      
  </div>
  
</div>
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71