3

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

Magikarp
  • 492
  • 6
  • 19
  • can we get some css codes for this? – Bellian Sep 06 '17 at 09:08
  • 1
    check borders, paddings and margins – godblessstrawberry Sep 06 '17 at 09:22
  • Typically, an element's offsetWidth is a measurement which includes the element borders, the element horizontal padding, the element vertical scrollbar (if present, if rendered) and the element CSS width. https://stackoverflow.com/questions/8133146/difference-between-style-width-and-offsetwidth-in-html – Milad Sep 06 '17 at 09:52
  • https://i.stack.imgur.com/S4DuJ.jpg There's nothing in it. Although I am using external stylesheet, so I dont know if that affects anything... Edited it to include css. – Magikarp Sep 06 '17 at 10:02

1 Answers1

0

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 .

andrew s zachary
  • 167
  • 2
  • 14