为什么我绝对定位的元素没有位于我期望的位置?

为什么我绝对定位的元素没有位于我期望的位置?,第1张

为什么我绝对定位的元素没有位于我期望的位置

为了正确理解这一点,您需要参考官方规范,在其中找到元素 必须 满足的方程式:

'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

如果您阅读下面的内容,将会发现:

  1. ‘top’和’bottom’为’auto’并且’height’不是’auto’, 然后将’top’设置为静态位置 ,将’margin-
    top’和’margin-bottom’的’auto’值设置为0 ,并解决“底部”问题。

因此,在您的情况下,您已经设置了高度并保持

top
/
bottom
为自动,因此top将被设置为 静态位置

更精确地说,“顶部”的静态位置是从包含块的顶部边缘到假设框的顶部边缘的距离,该假设框如果元素的指定“位置”值具有一直是“静态”

为简单起见,如果未设置,则为元素的位置

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 >  <div ></div>  <div  >I am static</div></div><div >  <div ></div>  <div ></div></div>

请注意,如果添加,第一个元素的静态位置将保留

position:absolute
。我们没有指定任何最高值,因此浏览器将使用默认值,该
position:static
默认值是元素(默认位置)之一。

如果您不希望这样做,只需设置最高值,然后遵循以下规则:

  1. ‘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;

    }

    I am static

同样的逻辑适用于left属性


您可能还会注意到 包含 单词_的块_的使用,这在这里非常重要并在同一规范中进行了说明。

有时会相对于某个矩形(称为元素的包含块)来计算元素框的位置和大小。元素的包含块定义如下:

  1. 如果元素具有“位置:绝对”,则包含块由最接近的祖先以“绝对”,“相对”或“固定”的“位置”建立,方法如下:

而且这还不够,因为还有其他属性(下面列出)也建立了一个包含块,因此您可以相对于未定位的祖先定位元素!



欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5440411.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-11
下一篇 2022-12-11

发表评论

登录后才能评论

评论列表(0条)

保存