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

3
我试图使用nativeElement.offsetWidth获取元素宽度,但它比实际宽度小了2.5像素。我想知道我错过了什么?
我尝试检查DOM并寻找2.5像素的位置,但是我无法在任何地方找到它:
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.5像素,但offsetWidth只返回327像素。
    .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


我们能获取一些针对此的 CSS 代码吗? - Bellian
1
检查边框、内边距和外边距。 - godblessstrawberry
通常,元素的offsetWidth是一个包括元素边框、元素水平填充、元素垂直滚动条(如果存在且已呈现)和元素CSS宽度的测量值。 - Milad
里面什么也没有。虽然我正在使用外部样式表,所以我不知道这是否会影响任何东西... 编辑它以包括 CSS。 - Magikarp
1个回答

0

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

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接