CSS position:absolute 定位
是相当于body 还是父级元素

position:absolute 定位是一个相对麻烦的问题

在文档流中 定义为position:absolute的元素已经被删除了
那它的定位到底是相对于body 还是父级元素呢?

结论
position:absolute
相对于他的包含块中第一个有position:absolute
或者position:relative属性的父级元素
如果都没有 就是相对于body

举例

1  父级元素都没有 就是相对于body定位的
复制代码
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div style="width:200px;height:200px;background-color:red;">
<div style="width:100px;height:100px;background-color:blue;">
    <div style="width:50px;height:50px;background-color:yellow;position:absolute;left:20px;top:10px;"></div>
</div>
</div>
</body>
</html>


2 父级元素里有 就是相对于哪个有的父级元素

相对于第一个div定位
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div style="width:200px;height:200px;background-color:red;position:absolute;">
  <div style="width:100px;height:100px;background-color:blue;">
      <div style="width:50px;height:50px;background-color:yellow;position:absolute;left:20px;top:10px;"></div>
  </div>
</div>
</body>
</html>

 

相对于第二个div定位
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div style="width:200px;height:200px;background-color:red;position:absolute;">
  <div style="width:100px;height:100px;background-color:blue;position:relative;">
      <div style="width:50px;height:50px;background-color:yellow;position:absolute;left:20px;top:10px;"></div>
  </div>
</div>
</body>
</html>