Html 嵌套 div 大于父 div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9593721/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:58:14  来源:igfitidea点击:

Nested divs bigger than parent div

csshtml

提问by F21

I am using CSS to skin a scroll bar that is created using JavaScript.

我正在使用 CSS 为使用 JavaScript 创建的滚动条设置外观。

.scrollbar-track{
    background: black;
    height: 10px;
}
 
.scrollbar-thumb{
    cursor: default;
    border: 1px red solid;
    width: 50px;
    padding: 0;
}

.scrollbar-thumb-first{
    display: inline-block;
    background: green;
    width: 5px;
    height: 10px;
}
 
.scrollbar-thumb-middle{
    display: inline-block;
    background: red;
    height: 10px;
    width: 20px;
}
 
.scrollbar-thumb-last{
    display: inline-block;
    background: blue;
    width: 5px;
    height: 10px;
}
<div class="scrollbar">
    <div class="scrollbar-track" style="width: 970px;">
        <div class="scrollbar-thumb">
            <span class="scrollbar-thumb-first"></span>
            <span class="scrollbar-thumb-middle"></span>
            <span class="scrollbar-thumb-last"></span>
        </div>
    </div>
</div>

And this is the fiddle: http://jsfiddle.net/w27wM/8/

这是小提琴:http: //jsfiddle.net/w27wM/8/

Why is the inner div somehow larger than the parent div? Even with margin and paddings set to 0, the issue still remain.

为什么内部 div 比父 div 大?即使边距和填充设置为 0,问题仍然存在。

采纳答案by F21

Issue resolved by changing all the display: inline-blockto float: left.

通过将所有更改display: inline-blockfloat: left.

The problem may be related to this question, but removing all the whitespace didn't fix it for me. This might be due to the node being created in javascript.

问题可能与此问题有关,但删除所有空格并没有为我解决。这可能是由于节点是在 javascript 中创建的。

回答by sreejesh

Its a simple problem. By default the span line-height is 20px. An inline-block element read line-height to vertical-align.

这是一个简单的问题。默认情况下,跨度 line-height 是 20px。内联块元素读取行高到垂直对齐。

So solution is either specify

所以解决方案是指定

line-height: 10px; or float: left;

Eg:

例如:

.scrollbar-thumb span{
   line-height: 10px;
}

or

或者

.scrollbar-thumb span{
   float: left;
}

回答by ghbarratt

The .scrollbar div is not given an explicit width so it assumes the default = 100% of the width given by its parent.

.scrollbar div 没有给出明确的宽度,因此它假定默认值 = 其父级给出的宽度的 100%。

The .scrollbar-track is given an explicit width of 970px which is beyond the width of the parent and the parent's parent. Thus, .scrollbar ends up thinner than its wide child .scrollbar-track.

.scrollbar-track 的显式宽度为 970px,超出了父级和父级父级的宽度。因此,.scrollbar 最终比它的宽子 .scrollbar-track 更薄。

Why are you setting the scrollbar-track explicitly but not doing the same for the .scrollbar (parent)?

为什么要显式设置滚动条轨道,但不对 .scrollbar(父项)执行相同操作?