原来我一直以来对于CSS的绝对定位(position:absolute)都存在误解,一直以来我以为绝对定位是相对于document画布的,今天看来W3School的教程,才发现:绝对定位的元素的位置相对于最近的已定位祖先元素,如果元素没有已定位的祖先元素,那么它的位置相对于最初的包含块。根据用户代理的不同,最初的包含块可能是画布或 HTML 元素。
在下例中,samplediv的绝对位置是相对于grandfatherdiv的,不相对于document,也不是相对于fatherdiv,由于fatherdiv采用的不是绝对定位。
<html> <head> <style type="text/css"> .samplediv { position:absolute; left:100px; top:150px; width:80%; background-color:red; } .grandfatherdiv{ position:absolute; left:40px; top:50px; background-color:#880099; width:100%; } .fatherdiv{ left:40px; top:50px; margin:10; background-color:blue; width:100%; } </style> </head> <body> <div class="grandfatherdiv"><div class="fatherdiv"><div class="samplediv">这是带有绝对定位的标题</div></div></div> </body> </html>