【问题标题】:Why is the element width not matching offsetWidth?为什么元素宽度与 offsetWidth 不匹配?
【发布时间】:2018-02-14 16:46:39
【问题描述】:

我尝试使用 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;
    }
}

【问题讨论】:

  • 我们能得到一些css代码吗?
  • 检查边框、内边距和边距
  • 通常,一个元素的 offsetWidth 是一个度量,它包括元素边框、元素水平填充、元素垂直滚动条(如果存在,如果呈现)和元素 CSS 宽度。 stackoverflow.com/questions/8133146/…
  • i.stack.imgur.com/S4DuJ.jpg 里面什么都没有。虽然我使用的是外部样式表,所以我不知道这是否会影响任何东西......编辑它以包含 css。

标签: html css angular angular2-components offsetwidth


【解决方案1】:

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

注意:如果你不使用cssreset,你肯定需要它来解决这样的问题。

【讨论】:

    猜你喜欢
    • 2021-12-24
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 2016-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    相关资源
    最近更新 更多