绝对定位和float的关系
1 文档流与非文档流
1.1 文档流
就是按照上下左右的顺序一行一行排列的,长度不够就会自动挤到下一行。
代码如下
<html>
<head>
<title></title>
<meta content="text/html; charset=GB2312" />
<style>
.a{border:1px solid red;width:960px;margin:0 auto;}
.b{ height:100px;width:100px;background-color:#aaa; top: 0;left: 0; }
.c{height:50px;background-color:#ddd;} </style>
</head>
<body>
<div class = "a">
<div class = "b"></div>
<div class = "c"></div>
</div>
</body>
</html>
1.2 非文档流
非文档流:顾名思义就是脱离普通流的,在普通流上面是不占据位置的。css有position的样式,position包括:static,relative,absolute,fixed四种值。其中static是属于普通流;relative也是属于特殊的普通流,详细下面有介绍;absolute和fixed以及float就是属于非普通流的,加载的时候,也会顺序加载,但是会脱离普通流的位置。
代码如下
<html>
<head>
<title></title>
<meta content="text/html; charset=GB2312" />
<style>
.a{border:1px solid red;width:960px;margin:0 auto;}
.b{ height:100px;width:100px;background-color:#aaa; top: 0;left: 0; float: left; }
.c{height:50px;background-color:#ddd;}
</style>
</head>
<body>
<div class = "a">
<div class = "b"></div>
<div class = "c"></div>
</div>
</body>
</html>
2 绝对定位和float的区别
CSS中脱离文档流,也就是将元素从普通的布局排版中拿走,其他盒子在定位的时候,会当做脱离文档流的元素不存在而进行定位。
需要注意的是,使用float脱离文档流时,其他盒子会无视这个元素,但其他盒子内的文本依然会为这个元素让出位置,环绕在周围。
而对于使用absolute脱离文档流的元素,其他盒子与其他盒子内的文本都会无视它。
浮动:float
<html>
<head>
<title></title>
<meta content="text/html; charset=GB2312" />
<style>
.a{border:1px solid red;width:960px;margin:0 auto;}
.b{
height:100px;width:100px;background-color:#aaa; float: left;
}
.c{height:50px;background-color:#ddd;}
</style>
</head>
<body>
<div class = "a">
<div class = "b"></div>i am float
<div class = "c"></div>
</div>
</body>
</html>
这时文字会环绕在浮动的盒子周围
绝对定位position
<html>
<head>
<title></title>
<meta content="text/html; charset=GB2312" />
<style>
.a{border:1px solid red;width:960px;margin:0 auto;position: relative;}
.b{
position: absolute;height:100px;width:100px;background-color:#aaa; top: 0; left: 0;
}
.c{height:50px;background-color:#ddd;}
</style>
</head>
<body>
<div class = "a">
<div class = "b"></div> position: absolute
<div class = "c"></div>
</div>
</body>
</html>
这时文字无视盒子,依旧按传统文档流进行平铺,所以位于盒子的下面。
3 absolute和float,display:inline-block的层级关系
绝对定位是一种脱离文档流的定位,被设置为绝对定位的元素,会找一个参照,先找父元素,查看父元素是否被设置为绝对或相对定位,有的话,视其为参照,如果没有,则继续往上找,直到html元素,以窗口作为参照,注意:被设为绝对定位的元素,可以不用管元素是否是块元素,可以直接设置宽高。
绝对定位始终在浮动定位的上面
再次改动层级
运行结果同样如上,可看出同样是脱离文档流,可position absolute 在float 的层级之上;
将float 改成display 为inline-block 和block ,更加改变不了position: absolute 元素和 在文档流上的元素 的层级了。
因此,在同一父元素里面,尽量避免absolute 和float 定位 同时使用。以免造成不必要的层级混乱问题。