使用CSS来定位页面内层的位置,一直是比较难以掌握的事情,很多时候,往往被绝对定位的元素,总是以浏览器的左上角为坐标原点,此时,如果浏览器的大小改变,被定义的层就会偏离设计想要的位置,让人很挠头。
其实,要想控制好层的绝对定位,只要理解CSS中关于定位(position)的定义,一切就会变得轻松简单。
CSS中关于定位(position)是这样定义的:
定位(position)允许用户精确定义元素框出现的相对位置,可以相对于它通常出现的位置,相对于其上级元素,相对于另一个元素,或者相对于浏览器视窗本身。每个显示元素都可以用定位的方法来描述,而其位置由此元素的包含块来决定的。
包含块(containing block)是格式编排发生的关联场景,例如,一个加粗的元素的包含块可以是该元素所出现的段落,如图1所示。

在理解定位之前,首先,要先理解HTML文件的结构,例如有一个html文件内容如下:

<html>

<head>

<metahttp-equiv="Content-Type"content="text/html;charset=gb2312"/>

<title>文档结构</title>

</head>

<body>

<h1>CSS规则</h1>

<p>样式表由一些<strong>样式规则</strong>组成。</p>

<ul>

<li>选择符

<ul>

<li>类选择符</li>

<li>ID选择符</li>

<li><em>包含</em>选择符</li>

</ul>

</li>

<li>属性</li>

<li>值</li>

</ul>

</ul>

</body>

</html>
此文档对应的树型结构,如图2所示。

CSS大部分能力是基于元素的“父子”关系,在图2的家族树中,每个元素都是另一个元素的“父”或者“子”或者两者都是。例如:body既是html的子元素,又是h1的父元素,而html就是h1的祖先,h1则是html的子孙。
Body是所有浏览器能显示的元素的祖先,而html是所有元素的祖先,也称为“根元素”。
那为什么定位了的元素还总是以浏览器窗口的左上角为坐标呢?
因为并不是每个元素都能为其后辈元素生成一个包含块。
建立包含块的规则如下:
“根元素”的包含块(也叫初始包含块)由用户代理生成,在HTML中,根元素是HTML元素,尽管有的浏览器会不正确地使用body元素。
对于那些未绝对定位的非根元素来说,元素的包含块设置为最近的块级祖先元素的内容区边沿。
对那些使用绝对(absolute)作为定位(postition)的非根元素,包含块设为最近的定位(postition)不是静止(static)的祖先元素(任何类型)。有以下几种情况:
如果祖先元素是块级(block)元素,包含块设为祖先元素的填充(padding)边沿,也就是被边框(border)约束的区域。
如果祖先元素是内联(inline)元素,包含块设为祖先元素的内容边沿。
关于包含块,最重要的是要记住它为所有后辈元素建立了一个格式编排的上下文。另一个重要方面是,元素可定位于它们的包含块之外。
因此,绝对定位的元素往往以浏览器可视区域的左上为坐标原点来进行定位了。
在CSS中可是使用position属性来在不同的定位类型中选择。
语法:
position : static | absolute | fixed | relative | inherit
其各参数含义是:
static : 静态(默认),无特殊定位。
relative : 相对,对象不可层叠,但将依据left,right,top,bottom等属性在正常文档流中偏移位置
absolute : 绝对,将对象从文档流中拖出,使用left,right,top,bottom等属性进行绝对定位。而其层叠通过z-index属性定义。此时对象不具有边距,但仍有补白和边框。
fixed : 悬浮,使元素固定在屏幕的某个位置,其包含块是可视区域本身,因此它不随滚动条的滚动而滚动。(IE5.5 不支持此属性。)
inherit : 这个值从其上级元素继承得到。
示例:


div{...}{position:absolute;bottom:1in;left:1in;right:1in;top:1in;}


div{...}{position:relative;top:-3px;left:6px;}
既然了解了包含块的概念,那么对于相对定位和绝对定位的关系,就很好掌握了。
例如,现在需要把页面内容整体居中,然后再将其中某些层绝对定位的话,那就要把最外面的层设置定位属性。

<body>

<divid="box">

<divid="nav">

<p>每个显示元素都可以用定位的方法来描述,而其位置由此元素的<strong>包含块</strong>来决定的。</p>

</div>

</div>

</body>
此时,如果你要对nav绝对定位,则需设置css:


body{...}{

margin:0;

padding:0;

text-align:center;

}


#box{...}{

background:#ff0;


position:relative;/**//*使box层成为其子孙元素的包含块*/

width:500px;

height:200px;

margin:0auto;

}


#nav{...}{

background:#ccc;


position:absolute;/**//*nav层将在box层的边框范围内绝对定位*/

top:20px;

left:40px;

width:200px;

}
其显示效果如图3所示。

因此,掌握了包含块的概念,定位就变得不那么困难了。
本文部分知识来源于:《CSS权威指南》