admin管理员组文章数量:1610898
absolute 绝对定位
1、在不同层面显示,把原来的位置腾出来,让后面的元素补上,最终形成了有position:absolute的元素显示在上层
<div class="demo1"></div>
<div class="demo2"></div>
.demo2 {
width: 150px;
height: 150px;
background: green;
}
.demo1 {
position: absolute;
margin-left: 100px;
width: 100px;
height: 100px;
background: black;
opacity: .5;
}
注:只要设置了position: absolute;的元素, 不管你有没有设置top,left,right,bottom的值,都会使得该元素脱离原来位置,别的元素里面会占满该位置
2、脱离原来的位置进行定位,最近有定位的父级进行定位,如果没有,那么相对与文档进行定位
-
demo3中加入 position: absolute;
其他的正常(不加定位),你看到的demo3,它会去找父级是否有定位,
如果父级没有定位就继续往上找,如果都没有,那么就相对于文档进行定位,
最终demo3的位置就在离左边50px的位置
<div class="demo1"> <div class="demo2"> <div class="demo3"></div> </div> </div> .demo1 { margin-left: 100px; width: 150px; height: 150px; background: green; } .demo2 { width: 100px; height: 100px; background: black; } .demo3 { position: absolute; left:50px; width: 50px; height: 50px; background: yellow; }
-
demo3中加入 position: absolute; demo2和demo1中都加入position: relative; demo3就会 直会先对于demo2定位,不会去管demo1的定位了
.demo1 { position: relative; margin-left: 100px; width: 150px; height: 150px; background: green; } .demo2 { position: relative; margin-left:50px; width: 100px; height: 100px; background: black; } .demo3 { position: absolute; width: 50px; height: 50px; background: yellow; }
relative
保留原来位置进行定位
-
在没有加入定位之前是这样的
<div class="demo2"></div> <div class="demo1"></div> .demo1 { width: 150px; height: 150px; background: green; } .demo2 { width: 100px; height: 100px; background: black; }
- 加入之后 保留了原来的位置进行定位,虽然你元素移动了但是你还在原来的地方占了位置
<div class="demo2"></div>
<div class="demo1"></div>
.demo1 {
width: 150px;
height: 150px;
background: green;
}
.demo2 {
position: relative;
top: 50px;
width: 100px;
height: 100px;
background: black;
}
相对于自己原来的位置进行定位
demo3中加入相对定位 position: relative;
.demo1 {
margin-left: 100px;
width: 150px;
height: 150px;
background: green;
}
.demo2 {
width: 100px;
margin-left: 50px;
height: 100px;
background: black;
}
.demo3 {
position: relative;
width: 50px;
height: 50px;
background: yellow;
}
- 在没有设置 top,left,right,bottom的值的时候他还在原来的位置,只是层级发生了改变
- 给demo3添加left:50px;值时位置发生了变化,相当于相对原来位置向左平移了50px
- 给demo3添加right:50px;值时位置发生了变化,相当于相对原来位置向右平移了50px
总结:absolute和relative到底怎么使用?
如果你想定位一个东西最好找参照物,你没有参照物瞎定位肯定时是不准的,
要定位需要两个东西,一个是参照物,一个是要它有定位,
一般情况下我们是这么配合的,只用relative作为参照物,不用来进行定位,用absolute进行定位
元素只设置relative,不设置top,right,left,bottom的值不会对元素有影响,还是在原来的位置,
而absolute可以任意的调换自己的参照物,定位起来更灵活
本文标签: PositioncssRelativeabsolute
版权声明:本文标题:对css中position的absolute和relative的理解 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://www.elefans.com/dongtai/1728603863a1165202.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论