相对定位和绝对定位的学习

相对定位和绝对定位的学习

相对定位

3个div,给3个颜色

style:
#div1{
width:100px;
height:100px;
background-color: red}
#div2{
width:100px;
height:100px;
background-color: blue}
#div3{
width:100px;
height:100px;
background-color: yellow}
三个DIV
修改了div2蓝色div的位置:
#div2{
width:100px;
height:100px;
background-color: blue;
margin-left:100px;
margin-top:100px;}

在这里插入图片描述

现在使用相对定位修改div2的位置
#div2{
width:100px;
height:100px;
background-color: blue;
margin-left:100px;
margin-top:100px;
position:relative;
right:100px;
bottom:100px;
}

效果是
在这里插入图片描述
再次修改
#div2{
width:100px;
height:100px;
background-color: blue;
margin-left:100px;
margin-top:100px;
position:relative;
top:100px;
}
效果是
在这里插入图片描述
相对定位:是相对于元素本来的位置,以本来的位置为参照物来移动,不脱离文档流,保留元素原来的位置。

绝对定位

2个DIV如下图

.main{
width:500px;
height:500px;
background-color: red;
margin-left:100px;

}

.left{
width:100px;
height:100px;
background-color: blue;

}
在这里插入图片描述
给蓝色div一个绝对定位
.main{
width:500px;
height:500px;
background-color: red;
margin-left:100px;

}

.left{
width:100px;
height:100px;
background-color: blue;
position:absolute;left:1px;

}
此时定位是以body作为参照物的,效果如下:
在这里插入图片描述
而当给父标签一个position定位时
.main{
width:500px;
height:500px;
background-color: red;
margin-left:100px;
position:absolute;
}

.left{
width:100px;
height:100px;
background-color: blue;
position:absolute;left:1px;
}

蓝色div回到了父元素里,以父元素作为参照物了,效果如下:
在这里插入图片描述
绝对定位是元素以参照物为参照进行偏移,是元素脱离文档流,原来的位置由其他元素所占据,参照物为上级有定位属性的元素,一级一级往上找到有定位属性的祖先元素位置,如果没有,则以页面为参照物。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值