【分享】说说标准——CSS核心可视化格式模型(visual formatting model)之十一:绝对定位
在前面的帖子中,我们已经讲了可视化模型中布局的两大方面:1. 常规流 2. 浮动,布局3大部分只剩下了绝对定位。前面的帖子中也零星的提到过关于绝对定位的某些特性,但都不够细致系统。
绝对定位(Absolute positioning)
相对包含块偏移定位
在绝对定位模型中,一个框明确地基于它的包含块偏移。不是父元素,这点需注意。
要是人家问你,绝对定位相对于谁定位啊?你很快乐的说:它的父元素。那就显得矬了- -!
专业的说法,相对于包含快定位。所以,绝对定位元素的定位,关键是包含块,什么是包含块?见:【分享】说说标准——CSS核心可视化格式模型(visual formatting model)之一:包含块(containing block)
完全脱离常规流
它完全脱离了常规流(对后继的兄弟节点没有影响)。
这一点又与浮动元素不同,好歹浮动元素会对后继的行框产生影响,而且,后面声明的绝对定位元素也不会受前面定义的绝对元素的影响。
可以这么理解,常规流中的元素,都在同一个层上,浮动是处于常规流之上的一个特殊层,可能会对常规流中的元素有影响。但是绝对定位的元素不会,可以把每个绝对定位的框看做一个单独的图层,独来独往。所以,说它完全脱离了常规流也不无道理。
注意一点,绝对元素定位的 top 和 left 值跟绝对元素未脱离常规流之前在常规流中位置有关。
看这个例子:
<div style="position:absolute; width:100px; height:100px; background-color:red;"> absolute</div><div style="height:50px; border:1px solid blue; width:200px;">DIV 中的普通文本元素</div><div style="position:absolute; left:60px; width:100px; height:100px; background-color:green;"> absolute</div>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"><HTML><HEAD> <TITLE>A frame document with CSS2</TITLE> <STYLE type="text/css"> BODY { height: 8.5in } div { border: 1px solid red; } /* Required for percentage heights below */ #header { position: fixed; width: 100%; height: 15%; top: 0; right: 0; bottom: auto; left: 0; } #sidebar { position: fixed; width: 10em; height: auto; top: 15%; right: auto; bottom: 100px; left: 0; } #main { position: fixed; width: auto; height: auto; top: 15%; right: 0; bottom: 100px; left: 10em; } #footer { position: fixed; width: 100%; height: 100px; top: auto; right: 0; bottom: 0; left: 0; } </STYLE></HEAD><BODY><DIV id="header"> ...</DIV><DIV id="sidebar"> ...</DIV><DIV id="main"> ...</DIV><DIV id="footer"> ...</DIV></BODY></HTML>