position:relative与position:absolute区别(示例展示)

在做一些demo的时候始终都分不清这两者的使用区别,也困扰了很久,今天下决心一定要弄清楚。

  • relative(相对定位) 对象不可层叠、不脱离文档流,参考自身静态位置通过 top,bottom,left,right 定位,并且可以通过z-index进行层次分级。如果对一个元素进行相对定位,它将出现在它所在的位置上。然后,可以通过设置垂直或水平位置,让这个元素“相对于”它的起点进行移动。如果将top设置为20像素,那么框将出现在原位置顶部下面20像素的地方。如果将left设置为20像素,那么会在元素左边创建20像素的空间,也就是将元素向右移动。
  • 示例
    html内容:
<div class="box" id="one">One</div>
<div class="box" id="two">Two</div>
<div class="box" id="three">Three</div>
<div class="box" id="four">Four</div>

css内容:

.box {
  display: inline-block;
  width: 100px;
  height: 100px;
  background: red;
  color: white;
}

#two {
  position: relative;
  top: 20px;
  left: 20px;
  background: blue;
}

-显示效果
在这里插入图片描述

  • absolute(绝对定位) 脱离文档流,通过 top,bottom,left,right 定位。选取其最近一个最有定位设置的父级对象进行绝对定位,如果对象的父级没有设置定位属性,absolute元素将以body坐标原点进行定位。
    html部分
1.有父级元素的情况
<div class="div1" >
		<div class="div2"></div>
</div>
	.div1{
		position: relative;
		width: 200px;
		height: 200px;
		background-color: blueviolet;
		margin-left: 100px;
	}
	.div2{
		margin-left: 100px;
		position: absolute;
		width: 50px;
		height: 50px;
		background-color: red;
	}
  • 实现效果
    在这里插入图片描述
2.没有父级元素的情况

absolute元素将以body坐标进行定位
html部分:

    <div class="box" id="one">One</div>
	<div class="box" id="two">Two</div>
	<div class="box" id="three">Three</div>
	<div class="box" id="four">Four</div>

css部分

	.box { 
   display: inline-block; 
   background: red; 
   width: 100px; 
   height: 100px; 
   float: left; 
   margin: 20px; 
   color: white; 
}

#three { 
   position: absolute; 
   top: 20px; 
   left: 20px; 
}
  • 实现效果
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值