错误的HTML DIV宽度

Inf*_*ies 2 html css css3

我有3个DIV.中间包含两个DIV.中间div内的两个DIV应该出现在彼此之上.我做了一个关于这个概念的样本:样本

<div style="background-color:blue; width:100%; height:100px;"></div>
<div style="width:100%; height:100px; background-color:green">
    <div style="background-color:red; width:100%; height:100px; position:absolute; z-index:0;"></div>
    <div style="background-color:yellow; width:100%; height:100px; position:absolute; z-index:1;"></div>
</div>
<div style="background-color:blue; width:100%; height:100px;"></div>
Run Code Online (Sandbox Code Playgroud)

所有DIV的宽度都是100%,但我不知道为什么,但中间div比其他人大.这是为什么?

SW4*_*SW4 6

中间(黄色)一个较大,因为它已position:absolute设置.这意味着当它计算宽度(100%)时,计算基于最近的具有positionset的祖先.由于没有父div有这个,它从body元素获取它,默认情况下定义了padding/width,导致意外的宽度计算.

你可以纠正这个问题:

body{
    padding:0;
    margin:0;
}
Run Code Online (Sandbox Code Playgroud)

或者通过添加position:relative到父元素.虽然你可能会也想删除paddingbody

演示小提琴