absolute定位元素的包含块为最近的position为非static的祖辈元素,若祖辈元素中没有定位元素,则包含块为初始包含块,在浏览器中为浏览器视口。
fixed定位是absolute定位的一种特殊表现。fixed定位元素的包含块为初始包含块,即视口。
两者包含块都为视口时,但有什么不同之处呢?
fixed定位元素相对于视口偏移,不随着body主体内容的滚动而滚动。
而absolute定位元素相对视口偏移时,仅指的是相对于滚动条处于顶端(document.body.scrollTop=0)时的视口的偏移,。在滚动过程中,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>