一、单独使用:css
relative:相对于自己偏移,没有脱离文档流。html
<div class="box">
<div class="box-item">box-item1</div>
<div class="box-item relative">box-item2</div>
<div class="box-item">box-item3</div> </div>
body{
margin: 0;
padding: 0;
background-color: #81d6d2;
}
.box{
width: 600px;
height: 200px;
margin: 50px;
background-color: #d6f5c3;
font-size: 0;
-webkit-text-size-adjust:none;
}
.box-item{
font-size: 14px;
background-color: darkorange;
width: 100px;
height:100px;
text-align: center;
line-height: 100px;
display: inline-block;
}
.relative{
position:relative;
top:20px;
left:20px;
background-color: lightcoral;
}
效果:web
能够看到它左偏移是相对于box-item1,而上偏移则是相对于父级box。所以说,它是相对于自身的位置偏移。浏览器
absolute:相对于浏览器定位,脱离了文档流,也就是不占位置。在没有设定TRBL值时是根据父级对象的坐标做为起始点,当设定TRBL值后则根据浏览器的左上角做为起始点,例子以下:spa
(没有设置TRBL,没有给top、left、bottom、right值).net
<style> body{
margin: 0;
padding: 0;
background-color: #81d6d2;
}
.box{
width: 200px;
height: 200px;
margin: 50px;
background-color: #d6f5c3;
}
.box-item{
position:absolute;
background-color: darkorange;
width: 100px;
height:100px;
text-align: center;
line-height: 100px;
}
</style>
<div class="box">
<div class="box-item">box-item</div>
</div>
效果:htm
(设置TRBL,没有给top、right、bottom、left值)对象
<style>
body{
margin: 0;
padding: 0;
background-color: #81d6d2;
}
.box{
width: 200px;
height: 200px;
margin: 50px;
background-color: #d6f5c3;
}
.box-item{
position:absolute;
top:20px;
left:20px;
background-color: darkorange;
width: 100px;
height:100px;
text-align: center;
line-height: 100px;
}
</style>
效果:blog
二、结合使用文档
relative和absolute结合使用时,能够再也不参照浏览器定位,而参照父级元素定位,从而更加自由。
<style>
body{
margin: 0;
padding: 0;
background-color: #81d6d2;
}
.box{
position:relative;
width: 200px;
height: 200px;
margin: 50px;
background-color: #d6f5c3;
}
.box-item{
position:absolute;
top:20px;
left:20px;
background-color: darkorange;
width: 100px;
height:100px;
text-align: center;
line-height: 100px;
}
</style>
效果:
总结:使用这个组合定位,可以实现相对父元素定位。单独使用relative只能相对自己偏移,单独使用absolute只能相对浏览器偏移,absolute受到父级元素是否有position影响。若是父级元素没有position值,则参照浏览器偏移,若是有(relative、absolute、fixed都行),则以父级元素为参照物偏移。
参考:
一、https://developer.mozilla.org/zh-CN/docs/Web/CSS/position#示例
二、https://www.imooc.com/qadetail/143797
三、https://blog.csdn.net/u012006632/article/details/50553140
四、http://www.jb51.net/css/68072.html