绝对定位
使用绝对定位的盒子以它的“最近”的一个“已经定位”的“祖先元素”为基准进行偏移。如果没有已经定位的祖先元素,就以浏览器窗口为基准进行定位。“已经定位”是指定义了除 static 之外的position。
普通文档流
运行代码:
<style>
div{ width: 100px;
height: 100px;
background-color: blue;
border: 2px red dashed;
}
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
</body>
</html>
运行结果:
绝对定位的盒子从标准流中脱离,对其后的兄弟盒子的定位没有影响,其他的盒子就好像这个盒子不存在一样。原先在正常文档流中所占的空间会关闭,就好像元素原来不存在一样。元素定位后,生成一个块级框,与原来它在正常流中生成的框无关。 比如:一群人排队,前面的人突然离开,后面的人自动补位,使队伍和之前一样。
运行代码:
<style>
article{
width: 300px;
height: 300px;
background-color: gray;
position: absolute;
}
#div1{
width: 100px;
height: 100px;
background-color: blue;
}
#div2{
width: 100px;
height: 100px;
background-color: red;
position: absolute;
left: 60px;
top: 80px;
}
#div3{
width: 100px;
height: 100px;
background-color: yellow;
}
</style>
</head>
<body>
<article>
<div id="div1">蓝 </div>
<div id="div2">红 </div>
<div id="div3">黄</div>
</article>
</body>
</html>
运行结果:
练习:
<style>
article{
width: 400px;
height: 400px;
background-color: gray;
position: absolute;
left: 400px;
top: 200px;
}
#div1{
width: 50px;
height: 50px;
background-color: white;
position: absolute;
left: 80px;
top: 50px;
}
#div2{
width: 50px;
height: 50px;
background-color: white;
position: absolute;
left: 280px;
top: 50px;
}
#div3{
width: 20px;
height: 20px;
background-color: green;
position: absolute;
left: 190px;
top: 190px;
}
#div4{
width: 40px;
height: 40px;
background-color: red;
position: absolute;
left: 180px;
top: 180px;
}
#div5{
width: 200px;
height: 50px;
background-color: white;
position: absolute;
left: 112px;
top: 250px;
}
</style>
</head>
<body>
<article>
<div id="div1"> </div>
<div id="div2"> </div>
<div id="div4"></div>
<div id="div3"></div>
<div id="div5"></div>
</article>
</body>
</html>
运行结果: