absolute定位元素的包含块问题

当absolute定位元素的祖辈元素都不是relative/absolute/fixed定位时,一直以为absolute元素是相对于视口定位的,跟fixed定位一样。但是实际情况是,absolute元素会随着文档的滚动而滚动,并不是在视口中固定不动的。那这种情况下absolute定位元素是相对于谁来定位的呢?
下面代码的效果怎么解释?(先向下滚动页面,然后点击页面使absolute元素定位。如果是相对于文档,那absolute元素应该是在文档的右下角。但实际上却不是)

 <html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<title>无标题文档</title>  
<style>  
html  
{  
    border-right:2px solid #f00;  
    width:200px;  
}  
body  
{  
    border-right:2px dotted #0f0;  
    width:100px;  
}  
div{  
    height:600px;  
}  
p.abPos{  
    position:absolute;  
    right:0px;  
    bottom:0px;  
    margin:0;  
    width:100px;  
    height:100px;  
    border:1px solid #00f;  
}  
</style>  
</head>  
<body>  
html宽度设为200px,右边框为红色;body宽度为100px,右边框为绿色;目标元素p(蓝色边框),绝对定位,包含块为视口,精确说包含块为窗口未滚动时的视口。  

<div>  
<p  width="300px" height="300px" id='target'></p>  
</div>  
<script>  
window.addEventListener('scroll',function(){  
    if(document.body.scrollTop>20){  
    document.getElementById('target').className='abPos';  
}  
});  
</script>  
</body>  
</html>

相对于页面的。。图片说明

@沃克先森,如果相对于页面,那absolute元素#target应该定位在文档的左下角。但事实很显然不是啊

position:absolute是相对于他的包含块中第一个有position:absolute或者position:relative属性的父级元素,如果都没有,就是相对于body。
不需要用js验证






无标题文档 html { border-right:2px solid #f00; width:200px; } body { border-right:2px dotted #0f0; width:100px; } div{ height:600px; } p.target{ position:absolute; right:0px; bottom:0px; margin:0; width:100px; height:100px; border:1px solid #00f; }





html宽度设为200px,右边框为红色;body宽度为100px,右边框为绿色;目标元素p(蓝色边框),绝对定位,包含块为视口,精确说包含块为窗口未滚动时的视口。




它应该相对于body的同一个水平线的位置跟随着移动,不会一直在右下角的

为了避免js误解,重新上个例子:‘祖辈元素中都没有定位’这个absolute元素的定位是在窗口右下角,而不是在body右下角。

  <html xmlns="http://www.w3.org/1999/xhtml">  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<title>无标题文档</title>  
<style>  
html  
{  
    border-right:2px solid #f00;  
    width:200px;  
}  
body  
{  
    border-right:2px dotted #0f0;  
    width:100px;  
}  
div{  
    height:600px;  
}  
p{  
    position:absolute;  
    right:0px;  
    bottom:0px;  
    margin:0;  
    width:100px;  
    height:100px;  
    border:1px solid #00f;  
}  
</style>  
</head>  
<body>  
html宽度设为200px,右边框为红色;body宽度为100px,右边框为绿色;目标元素p(蓝色边框),绝对定位,包含块为视口,精确说包含块为窗口未滚动时的视口。  
<div >
    <p  width="300px" height="300px" id='target'>祖辈元素中都没有定位</p> 
</div>
<div style='position:relative;'>  
<p  width="300px" height="300px" id='target'>相对父元素div定位</p>  
</div>   
</body>  
</html>

哥们你这不是为难自己吗 absolute需要有已定位的元素去定位,你试着在html上加position:relative 结果就完全能解释 ,但是像你现在啥都不加 按平时我们都会觉得是根据body或者html 但是这里有点其他bug 可能他是根据浏览器窗口定位,但是我们用的时候应该按套路来给父元素来个position:relative就是自己掌控范围了