2017-09-06 132 views
3

我试图让使用nativeElement.offsetWidth元素的宽度,但它比实际宽度较小2.5px。我想知道我错过了什么?为什么元素宽度不匹配offsetWidth?

我试图检查DOM并试图找到其中2.5px,但我不能在任何地方找到它:

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> 

例如,在devtool它显示329.5px但是offsetWidth只返回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

+0

我们可以得到一些这样的CSS代码? – Bellian

+1

检查边界,填充和边距 – godblessstrawberry

+0

典型地,元素的offsetWidth是测量,其包括该元素的边界,该元件水平填充,所述元件垂直滚动条(如果存在的话,如果呈现)和元件CSS宽度。 https://stackoverflow.com/questions/8133146/difference-between-style-width-and-offsetwidth-in-html – Milad

回答

0

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

注:,如果你不使用css重置你肯定需要它会解决问题这样。

+0

它并没有真正解决问题。不过谢谢 – user3327729

相关问题