您的位置:首页 > 其它

绝对定位和相对定位

2015-07-08 11:23 477 查看
相对定位元素设置position值:position:relative; 此属性值的设置,元素没有脱离文档流,还是普通流定位模型的一部分,会对文档流中其它元素布局产生影响首先给大家演示一个代码
<!DOCTYPE html>
<html>
<head>
<style>
.div1{background-color:red;height:100px}
.div2{background-color:green;height:50px;}
.div3{background-color:blue;height:30px}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
</body>
</html>
页面显示结果:接着我们将第二个div加入relative相对定位属性,他会保留原有位置,根据原有文档位置进行相对定位:
<!DOCTYPE html>
<html>
<head>
<style>
.div1{background-color:red;height:100px}
.div2{background-color:green;height:50px;position:relative;top:90px}
.div3{background-color:blue;height:30px}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div2"></div>
<div class="div3"></div>
</body>
</html>
需要注意的是相对定位并没有脱离文档流绝对定位设置position值:position:absolute; 此属性值的设置,元素从文档流完全删除绝对定位的元素的偏移位置以最近的定位(包括相对定位和绝对定位)祖先元素作参照物。如果元素没有已定位(包括相对定位和绝对定位)的祖先元素,那么它的参照物为最顶级元素(由于浏览器的默认参照物不同,物可能是BODY或 HTML 元素)。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.div1{background-color:red;height:100px;}
.div{background-color:yellow;height:50px;}
.div2{background-color:green;height:20px;}
.div3{background-color:blue;height:30px}
</style>
</head>
<body>
<div class="div1"></div>
<div class="div">
<div class="div2">
这是绝对定位元素
</div>
</div>
<div class="div3"></div>
</body>
</html>
显示如下:之后为div2设置absolute,如果
.div2{background-color:green;height:20px;position: absolute;}
如果没有指定绝对定位位置,则还是保留在原来的文档流中初始位置,若果指定位置后,就会销毁文档流中的位置。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.div1{background-color:red;height:100px;}
.div{background-color:yellow;height:50px;position: relative;top:20px}
.div2{background-color:green;height:20px;position: absolute;top:10px}
.div3{background-color:blue;height:30px}
</style>
</head>
<body>
<div class="div1">1</div>
<div class="div">
2
<div class="div2">
这是绝对定位元素
</div>
</div>
<div class="div3">3</div>
</body>
</html>

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: