很多资料都说 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级别更高的吗?
1.绝对定位元素是相对于它的包含块.
2.包含块的定义见下图:

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