要正确理解这一点,您需要参考官方规格在哪里可以找到方程的元素must满足:
'top' + 'margin-top' + 'border-top-width' + 'padding-top' + 'height' + 'padding-bottom' + 'border-bottom-width' + 'margin-bottom' + 'bottom' = height of containing block
我们没有任何边框和填充,因此在您的情况下它只是:
'top' + 'margin-top' + 'height' + 'margin-bottom' + 'bottom' = height of containing block
如果您阅读下面的内容,您会发现:
- “顶部”和“底部”是“自动”,“高度”不是“自动”,然后将“top”设置为静态位置,将“margin-top”和“margin-bottom”的“auto”值设置为0,并求解“bottom”。
所以在你的情况下,你已经设置了一个高度并保持top
/bottom
为 auto,因此 top 将被设置为静态位置
..更准确地说,“top”的静态位置是从包含块的上边缘到假设框的上边距边缘的距离,如果指定的“position”值具有,该假设框将是元素的第一个框一直是“静态”..
为了简单起见,如果您没有设置,它就是元素的位置position:absolute
.
这是一个简单的说明,以便更好地理解
.container {
background: lightblue;
position: relative;
padding:40px 20px;
display:inline-block;
vertical-align:top;
width: 250px;
}
.box-grey {
background: grey;
height: 100px;
width: 100px;
position: absolute;
}
.box-green {
height:20px;
background:green;
}
<div class="container">
<div class="box-green"></div>
<div class="box-grey" style="position:static;">I am static</div>
</div>
<div class="container">
<div class="box-green"></div>
<div class="box-grey">I am absolute</div>
</div>
请注意,如果我们添加,则保留的第一个元素的静态位置position:absolute
。我们没有指定任何顶部值,因此浏览器将使用默认值之一position:static
元素的(默认位置)。
如果您不希望这样,只需设置顶部值,您就会陷入以下规则:
- “bottom”是“auto”,“top”和“height”不是“auto”,然后将“margin-top”和“margin-bottom”的“auto”值设置为0并求解“bottom”
.container {
background: lightblue;
position: relative;
padding:40px 20px;
display:inline-block;
vertical-align:top;
width: 250px;
}
.box-grey {
background: grey;
height: 100px;
width: 100px;
position: absolute;
top:0;
}
.box-green {
height:20px;
background:green;
}
<div class="container">
<div class="box-green"></div>
<div class="box-grey" style="position:static;">I am static</div>
</div>
<div class="container">
<div class="box-green"></div>
<div class="box-grey"></div>
</div>
同样的逻辑适用于左边的财产
您可能还注意到这个词的使用包含块这在这里非常重要,并在相同规格
元素框的位置和大小有时是相对于某个矩形(称为元素的包含块)计算的。元素的包含块定义如下:
...
- 如果元素具有“position:absolute”,则包含块由最近的祖先以“position”为“absolute”、“relative”或“fixed”建立,如下所示:
...
这还不够,因为还有其他属性(如下所列)也建立了一个包含块,因此您可以将一个元素相对于未定位的祖先进行定位!
有关的:为什么在父级上应用 CSS 过滤器会破坏子级定位?