position:absolute
与float:left
有两大共性:包裹性,破坏性。
包裹性
包裹性即让元素inline-block
化,例如一个div
标签默认宽度是100%显示的,但是使用了absolute
属性,则100%默认宽度就会变成自适应内部元素的宽度。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<style type="text/css">
.div {
padding:20px;
margin-bottom:10px;
background-color:#f0f3f9;
}
.abs {
position:absolute;
}
</style>
</head>
<body>
<div class="div">
<p>无absolute</p>
</div>
<div class="div abs">
<p>absolute后</p>
</div>
</body>
</html>
float
也是典型的inline-block
化元素,这种使元素inline-block
化适用于任何的标签。例如让span
标签支持width
属性,如下设置:
span { display:block; width:100px; }
但是,使用了float:left
/position:absolute
之后就不需要使用display
属性。
span { float:left; width:100px; }
span { position:absolute; width:100px; }
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<style type="text/css">
.span0 {
width:100px;
margin-bottom:10px;
background-color:#f0f3f9;
}
.span1 {
display:block;
width:100px;
margin-top: 10px;
margin-bottom:10px;
background-color:#f0f3f9;
}
.span2 {
position:absolute;
width:100px;
background-color:#f0f3f9;
margin-bottom:10px;
}
</style>
</head>
<body>
<span class="span0">没有使用absolute没有使用display:block</span>
<span class="span1">没有使用absolute使用了display:block</span>
<span class="span2">使用absolute</span>
</body>
</body>
</html>
破坏性
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
</head>
<body>
<div style="border: 1px solid;margin-top:20px;">
<div style="float:left;width:100px;height:200px;background-color:red;"></div>
<div style="position:relative;left:150px;width:100px;height:100px;background-color:green;"></div>
</div>
<div style="border: 1px solid;position:relative;top:150px;">
<div style="position:absolute;width:100px;height:200px;background-color:red;">使用absolute对父div的影响</div>
<div style="position:relative;left:150px;width:100px;height:100px;background-color:green;"></div>
</div>
<div style="border: 1px solid;position:relative;top:300px;">
<div style="width:100px;height:200px;background-color:red;">不使用absolute对父div的影响</div>
<div style="position:relative;left:150px;width:100px;height:100px;background-color:green;"></div>
</div>
</body>
</html>
五、position:absolute滥用
absolute
属性本来是想把页面搞得像photoshop那样,一个图层一个图层覆盖。但是,页面的发展与这个背道而驰,毕竟页面是活的。
流动性布局很强调不定宽,不定高,活用标签自身属性,顺其自然,最少干预。但是由于absolute
属性(尤其是带有left
/top
值)的破坏性,会导致高宽塌陷,于是,只能设定一个高度值(或是足以撑开高度的值),例如新浪微博导航就是绝对定位,所以导航外标签必须定高,否则,下面的元素会上来发生重叠:
想重构高质量的页面,少用绝对定位布局!