absolute 相对谁定位?

很多资料都说 absolute 相对第一个非static父元素定位,如果没有就想对body。
写个demo,发现好像不是那么回事啊。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
    html {
      width: 80%;
      height: 100%;
      background-color: teal;
    }

    body {
      width: 50%;
      height: 100%;
      background-color: #ccc;
    }

    .box {
      position: absolute;
      right: 0;
      top: 0;
      width: 200px;
      height: 200px;
      background-color: red;

    }
  </style>
</head>

<body>
  <div class="box">absolute</div>
</body>

</html>

虽然文档在Firefox, safari, chrome效果不一样。
但可以看出绝对不是相对body,html来定位啊,还有肯定也不像fixed相对视口。
难道有什么不为人知的秘密?有比html级别更高的吗?

阅读 3.7k
3 个回答

1.绝对定位元素是相对于它的包含块.

The box's position (and possibly size) is specified with the 'top', 'right', 'bottom', and 'left' properties. These properties specify offsets with respect to the box's containing block.

2.包含块的定义见下图:
图片描述

3.将.box的定位改为bottom:0而不是top: 0;查看右下角的边界,截图如下:
图片描述 可见该元素就是相对于视窗的大小在进行定位。

默认,相对于屏幕,否则,你如果给其某个父元素设置position属性,则会相对于设置的父元素

默认是body,如果父级设置了position,则根据父级定位。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题