html - 为什么元素宽度与 offsetWidth 不匹配?

标签 html css angular angular2-components offsetwidth

我尝试使用 nativeElement.offsetWidth 获取元素宽度,但它比实际宽度小 2.5px。我想知道我错过了什么?

我试图检查 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

最佳答案

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

注意:如果您没有使用 css 重置,您肯定需要它来解决这样的问题。

关于html - 为什么元素宽度与 offsetWidth 不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46071057/

相关文章:

html - 使 bootstrap 4 单元格表现为条形图

javascript - 附加 Jquery 后绑定(bind)单击事件不起作用

html - 我想使用 css 在绝对定位的图像后面放置一个固定的背景

html - 如何根据行中的一列将行居中?

html - Angular 6 iframe 绑定(bind)

html - 根据屏幕大小调整内联列表的大小

html - 在 CSS 中指定命名颜色的数值

html - 响应式网格系统——他们为什么不排队?

javascript - 加载 gif 加载时间过长

regex - Angular 模式验证器未按预期工作