为了正确理解这一点,您需要参考官方规范,在其中找到元素 满足的方程式:
'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
/ bottom
为自动,因此top将被设置为 静态位置
更精确地说,“顶部”的静态位置是从包含块的顶部边缘到假设框的顶部边缘的距离,该假设框如果元素的指定“位置”值具有一直是“静态”
为简单起见,如果未设置,则为元素的位置position:absolute
。
这是一个易于理解的简单示例
.container {
background: lightblue;
position: relative;
padding:40px 20px;
display:inline-block;
vertical-align:top;
width: 250px;
}
.@R_166_2419@-grey {
background: grey;
height: 100px;
width: 100px;
position: absolute;
}
.@R_166_2419@-green {
height:20px;
background:green;
}
<div class="container">
<div class="@R_166_2419@-green"></div>
<div class="@R_166_2419@-grey" style="position:static;">I am static</div>
</div>
<div class="container">
<div class="@R_166_2419@-green"></div>
<div class="@R_166_2419@-grey"></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;
}
.@R_166_2419@-grey {
background: grey;
height: 100px;
width: 100px;
position: absolute;
top:0;
}
.@R_166_2419@-green {
height:20px;
background:green;
}
同样的逻辑适用于left属性
您可能还会注意到 包含 单词_的块_的使用,这在这里非常重要并在同一规范中进行了说明。
有时会相对于某个矩形(称为元素的包含块)来计算元素框的位置和大小。元素的包含块定义如下:
…
…