2017-09-06 60 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

相關問題