Get height of element with position:fixed

Viewed 1811

I'm trying to get the height of an element at run time. I have a navbar that becomes fixed when I scroll down. I want to set the padding of the container to equal the navbar's height (when fixed). The problem is that as soon as I set the position to fixed the offsetHeight becomes 0. I can get the height using the offsetHeight of the child elements and including margin/padding but I'm looking for a cleaner way.

This uses angular to add/remove classes.

<div class="nav-container" id="nvbr" (dblclick)="getHeight()">
  <app-navbar [fixed]="_fixed"></app-navbar>
</div>
<div [style.padding-top.px]="_fixed ? _navHeight : 0">
   <router-outlet></router-outlet>
</div>

Scroll event (this tells angular to add my fixed class to the element):

if (window.pageYOffset > 55) {
        if (this._fixed === false)
            this._fixed = true
    }
    else {
        if (this._fixed === true)
            this._fixed = false
    }//else

Getting height:

getHeight() {
    let navEl =   document.getElementById("nvbr")
    console.log(navEl, navEl.offsetHeight)
}

if I go into chrome and untick position:fixed; then I get the correct height

Any ideas?

1 Answers

So a solution I have used in the past is to nest a child div below with position set to relative and height set to 100%. (ensure no margin and padding is applied also). See the example below.

//css
.nav-container {
  position: fixed;
  height: 65px;
  padding: 0;
}

.nav-container-first-child{
  position: relative;
  height: 100%;
  margin: 0;
}
//html
<div class="nav-container" id="nvbr" (dblclick)="getHeight()">
  <div class="nav-container-first-child">
    <app-navbar [fixed]="_fixed"></app-navbar>
  </div>
</div>
//javascript
getHeight() {
    let navEl =   document.getElementById("nvbr")
    console.log(navEl.offsetHeight) //displays 0
    console.log(navEl.firstChild.offsetHeight) //displays 65
}

Instead of accessing offsetHeight, access the offsetHeight of the first child instead.

firstChild.offsetHeight

Alternatively, you could have something like the following styles below and it would still work or you could even remove the height element altogether. As long as the child element is the same height as the parent and no obscured by a margin or padding it will work.

//css
.nav-container {
  position: fixed;
  padding: 0;
}

.nav-container-first-child{
  position: relative;
  height: 65px;
  margin: 0;
}

I remember using a setup like this quite a lot to set header and content containers for mobile device pages.

Hope this helps.

Related