欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-04-24 20:53:10
...

在做一些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;
}

-显示效果
position:relative与position:absolute区别(示例展示)

  • 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;
	}
  • 实现效果
    position:relative与position:absolute区别(示例展示)

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; 
}
  • 实现效果
    position:relative与position:absolute区别(示例展示)