当绝对定位没有具有定位属性的父元素时,是相对浏览器窗口还是body或者html定位的?

当绝对定位没有具有定位属性的父元素时,是相对浏览器窗口还是body或者html定位的?

测试了下,给body和html左侧外边距,结果发现div块的位置并没有影响。所以是相对浏览器窗口定位的?

clipboard.png

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
        }
        html{
            margin-left: 100px;
            background-color: yellow;
        }

        body{
            margin-left: 10px;
            background-color: cornflowerblue;
            height: 500px;
        }
        div{
            position: absolute;
            left: 50px;
            top: 50px;
            background-color: deeppink;
            height: 300px;
            width: 300px;
        }
    </style>
</head>
<body>
    结果可以看出,当绝对定位的元素没有具有定位属性的父元素时,其是相对页面文档的边缘来进行定位的(html和body的外边距并没造成影响)。
    <div>
        测试绝对定位--无定位属性的父元素时的相对定位对象
    </div>
</body>
</html>
阅读 5k
3 个回答

首先MDN上原话:

绝对定位元素相对于最近的非 static 祖先元素定位。当这样的祖先元素不存在时,则相对于ICB(inital container block, 初始包含块)。

而根元素所在的包含块就叫初始包含块(ICB),所以也就是说当绝对定位的元素没有非 static定位属性的父元素时,相对于ICB定位。

根元素的包含块一般是视口(连续媒体)或者由页面区域(paged media)

CSS2规范对于包含块的定义中说到:

The containing block in which the root element lives is a rectangle called the initial containing block. For continuous media, it has the dimensions of the viewport and is anchored at the canvas origin; it is the page area for paged media. The 'direction' property of the initial containing block is the same as for the root element.

相对于 body

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