<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#test1{
width:400px;
height:400px;
background:green;
}
p{
margin:0px;
padding:0px;
}
#p1{
width:100px;
height:100px;
background:red;
}
#p2{
width:100px;
height:100px;
background:orange;
}
</style>
</head>
<body>
<div id="test1">
<p id="p1">相对定位是指元素在其正常的位置,偏移某些像素</p>
<p id="p2">相对定位是指元素在其正常的位置,偏移某些像素</p>
</div>
</body>
</html>
未添加相对定位偏移属性:
添加属性后:
#p1{
width:100px;
height:100px;
background:red;
position:relative;
top:20px;
left:20px;
}
如果要改变偏移方向只需直接更改偏移的方向即可,如:
#p1{
width:100px;
height:100px;
background:red;
position:relative;
/*top:20px;
left:20px;*/
right:20px;
bottom:20px;
}
绝对定位:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style>
#test1{
width:400px;
height:400px;
background:green;
}
p{
margin:0px;
padding:0px;
}
#p1{
width:100px;
height:100px;
background:red;
position:relative;
/*top:20px;
left:20px;*/
right:20px;
bottom:20px;
}
#p2{
width:100px;
height:100px;
background:orange;
}
#test2{
width:400px;
height:400px;
background:blue;
}
#p3{
width:100px;
height:100px;
background:gray;
}
</style>
</head>
<body>
<div id="test1">
<p id="p1">相对定位是指元素在其正常的位置,偏移某些像素</p>
<p id="p2">相对定位是指元素在其正常的位置,偏移某些像素</p>
</div>
<div id="test2">
<p id="p3">绝对定位相对于父元素的top,left,right,bottom来定位</p>
</div>
</body>
</html>
未写入绝对定位属性的效果:
写入绝对定位:
#p3{
width:100px;
height:100px;
background:gray;
position:absolute;
top:20px;
left:30px;
}
上面的效果为什么是这样的呢,因为用绝对定位时父元素要求有position属性才行,否则将依据父的父....一直到body, 哪个祖先有position属性,相对哪个祖先,如果都没有则相对于body。那么我们就为代码中的p3父元素设置一个position属性:
#p3{
width:100px;
height:100px;
background:gray;
position:absolute;
top:20px;
left:30px;
}
如果再添加一块的话会是什么效果呢:
#p4{
width:100px;
height:100px;
background:pink;
position:absolute;
top:30px;
left:40px;
}
</style>
</head>
<body>
<p id="p4"></p>
</div>
</body>
</html>
新增的粉红块漂浮在了灰块上方,那么要是想让灰块漂浮在粉块上方呢,可以用到一个属性z-index:取的值越大,哪块就会在上方效果如下:
#p3{
width:100px;
height:100px;
background:gray;
position:absolute;
top:20px;
left:30px;
z-index:10000;
}
转载于:https://blog.51cto.com/716870410/1558347