本文转载自HTML5学堂:HTML5_Course
今天给大家说说,position:absolute 参考谁进行定位的问题。之前大家可能会认为如果absolute元素的父级(祖父)元素没有设置position属性的时候,该元素的position:absolute会参考body进行定位。
换句话说是如果父级设置了position(且值为非static),参照(最近的)父级的内容区域的左上角为初始点,结合top left right bottom 进行定位; 如果没有设置,往其父级继续寻找,直到找到为止,如果一直没有,则相对与body进行定位(我们猜想是这样的,但是不一定是对哦~~)。
测试实例:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>HTML5Course - 梦幻雪冰</title> 6 <link rel="stylesheet" href="reset.css"> 7 <style> 8 /*正常是不能这么设置的,这边主要是用来测试*/ 9 html { 10 margin: 20px; 11 border: 20px solid red; 12 } 13 /*正常是不能这么设置的,这边主要是用来测试*/ 14 body { 15 height: 400px; 16 margin: 30px; 17 border: 20px solid green; 18 } 19 .wrap { 20 position: absolute; 21 top: 0; 22 left: 0; 23 width: 100px; 24 height: 100px; 25 background-color: pink; 26 } 27 </style> 28 </head> 29 <body> 30 <div class="wrap">梦幻雪冰</div> 31 </body> 32 </html>
测试结果:
Tips:图中红色边框为html元素,绿色边框为body元素
结论:测试数据发现如果定位的元素的父级(祖父)没有设置position属性的时候,不会参考body进行定位。
为了再次验证我们的结论,我们给body设置position属性(值为非static),看看结果会是如何?
测试实例:
1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>HTML5Course - 梦幻雪冰</title> 6 <link rel="stylesheet" href="reset.css"> 7 <style> 8 /*正常是不能这么设置的,这边主要是用来测试*/ 9 html { 10 margin: 20px; 11 border: 20px solid red; 12 } 13 /*正常是不能这么设置的,这边主要是用来测试*/ 14 body { 15 position: relative; 16 height: 400px; 17 margin: 30px; 18 border: 20px solid green; 19 } 20 .wrap { 21 position: absolute; 22 top: 0; 23 left: 0; 24 width: 100px; 25 height: 100px; 26 background-color: pink; 27 } 28 </style> 29 </head> 30 <body> 31 <div class="wrap">梦幻雪冰</div> 32 </body> 33 </html>
测试结果:
Tips:图中红色边框为html元素,绿色边框为body元素
看到结果,发现如果给body设置了position属性就正常了,所以我们之前的猜想是错误的,不是参考body进行定位的。
那么position:absolute是参考哪一个父级(祖父)元素进行定位的?
当给元素设置absolute的时候,它会往上查找 absolute 元素的第一个父元素,如果该父元素的 position 值存在(且不为 static),那么就是根据该父元素进行的定位,否则将会继续查找该父元素的父元素,一直追溯到某个父元素具备不为 static 的 position 值为止,如果不存在满足条件的父元素,则会根据最外层的 window 进行定位。
英文描述如下: