现在的位置: 首页 > 综合 > 正文

CSS中的Position属性

2011年05月15日 ⁄ 综合 ⁄ 共 2532字 ⁄ 字号 评论关闭

也许你看到这个标题觉得很简单,确实这是一篇关于CSS中Position属性基础知识的文章,但是关于Position的一些细节也许你不了解。

1、简介
 position有五个属性: static | relative | absolute | fixed | inherit
 static 和 inherit : 没什么值得介绍的。
 relative : 相对于元素自身的定位。
 absolute :相对于包含块的定位。
 fixed : 相对于窗口的定位。

2、包含块

包含块就是 top | right | bottom | left 参考的元素。
absolute的包含块指的是:该元素最近的具有定位设置的父元素,即最近的position属性值不为static的祖先元素举个例子:

 

<body>
<div id="outer" style="position:absolute">
<div id="inner">
<span style="position:absolute">span</span>
</div>
</div>
</body>

对于span元素来讲,它的包含块是#outer,而不是#inner,因为#outer设置了 position:absolute。值得注意的是,只要#outer设置了 absolute | relative | fixed span元素的“定位父元素”就是#outer,如果outer没有设置三种属性的其中之一,则span的包含块就是html元素。

relative的包含块指的是:元素自身。

3、top | right | bottom | left 的细节。
也许你会想当然的认为这些值有什么细节可言,那你就错了。在此以left为例:
left值 = “定位父元素”border内边 到 该元素margin外边的举例 ,简单的记忆就是“border内,margin外”。

right | bottom | left 也是这种道理

4、z-index
关于z-index的细节,这里就不说了,因为觉得自己表达不清,而且《CSS权威指南》相应章节里对z-index讲的非常清楚(特别是叠放上下文的相关知识),这些知识是非常有用的。
如果你能看懂下面这个层叠顺序,则证明你对z-index的学习已经非常成熟了。要注意其中#one1 元素 #two元素的层叠顺序。

例子:http://www.kangchangan.cn/cnblog/zIndexStackingContext.html

 

5、postion 与文档流
只要元素设置了 postion : absolute | relative | fixed , 该元素就会脱离文档流。
但是relative元素是个特例,因为该元素对然脱离了文档流,但是它原本所占的空间仍然占据文档流。

例如:

 

代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>relative</title>
<style type="text/css">
*
{ margin:0; padding:0;}
body
{ padding:50px; background-color:#FFFFCC;}
span
{
position
:relative;
left
:50px;
top
:40px;
background-color
:#FF9900;
}
</style>
</head>

<body>
<p> rain-man rain-man rain-man rain-man rain-man <br />
rain-man rain-man
<span>cnblog</span> rain-man rain-man <br />
rain-man rain-man rain-man rain-man
<br />
rain-man rain-man rain-man rain-man
<br />
rain-man rain-man rain-man rain-man
<br /></p>
</body>
</html>

6、positon 与 display
元素分为内联元素和区块元素两类(当然也有其它的),在内联元素中有个非常重要的常识,即内两元素是不可以设置区块元素所具有的样式,例如:width | height。
relative : 原来是什么类型的依旧是什么类型。
absolute | fixed : 元素就被重置为了区块元素,例如:打算为span元素指定大小,并绝对定位
     <span style="position:absolute; width:100px; height:50px;">span</span>这是完全正确的,
     <span style="position:absolute; display:block; width:100px; height:100px;">span</span>,这里的display:block就是多余的了。

7、position 与 float
一个元素若设置了 position:absolute | fixed; 则该元素就不能设置float。这是一个常识性的知识点,因为这是两个不同的流,一个是浮动流,另一个是“定位流(这是自己起的名字,呵呵)”。
但是 relative 却可以。因为它原本所占的空间仍然占据文档流。

8、Bug

Bug1:

 参考网页: http://therealcrisp.xs4all.nl/meuk/IE-zindexbug.html,哎这个就是IE的bug了,解决办法就是为#container设置 z-index:11 || 大于10的整数。

Bug2:

bug页面:http://www.kangchangan.cn/cnblog/floatPosition.html

解决页面:http://www.kangchangan.cn/cnblog/floatPosition2.html

 相关解释已经在解决页面了。

抱歉!评论已关闭.