Why is the element width not matching offsetWidth?

1.3k views Asked by At

I tried to get the element width using nativeElement.offsetWidth but it's 2.5px lesser than the actual width. I was wondering what I'm missing?

I tried to inspect the DOM and try to find where the 2.5px but I cant find it anywhere:

export class AppComponent implements OnInit { 
   @ViewChild('sidebarSection') sectionContainer:ElementRef;

   getNavbarWidth(){
       return this.sectionContainer.nativeElement.offsetWidth;        
   }
}


<body>
<div class='wrapper'>
    <div class='row'>
        <div class='cell col s3'>
            <div #sidebarSection>
                <nav-menu></nav-menu>
            </div>
        </div>
        <div class="cell col s9">
            <section Id='main'>
                <router-outlet>
                   ...
                </router-outlet>
            </section>
        </div>
    </div>
</div>

For example, on the devtool it shows 329.5px but the offsetWidth only returns 327px.

    .main-nav {
    box-sizing: border-box;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1;
}

.navbar-nav > li > a {
    color: wh
}

@media (min-width: 768px) {
    /* On small screens, convert the nav menu to a vertical sidebar */
    .main-nav {
        background-color: #56004e;
        height: 100%;
        width: calc(25% - 20px);
    }
    .navbar {
        background-color: #56004e;
        border-radius: 0px;
        border-width: 0px;
        height: 100%;
        margin-bottom: 0px;
    }
    .navbar-header {
        float: none;
    }
    .navbar-collapse {
        border-top: 1px solid #444;
        padding: 0px;
    }
}

enter image description here

1

There are 1 answers

0
andrew s zachary On

html {
  box-sizing: border-box;
}
*, *:before, *:after {
  box-sizing: inherit;
}

NOTE : if you are not using css reset you sure need it will solve issue like that .