您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

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

'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属性

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

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

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

其他 2022/1/1 18:18:04 有371人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶