position 属性规定元素的定位类型。
这个属性定义建立元素布局所用的定位机制。任何元素都可以定位,不过绝对或固定元素会生成一个块级框,而不论该元素本身是什么类型。相对定位元素会相对于它在正常流中的默认位置偏移。
常用的值:
1.relative (相对定位):生成相对定位的元素,相对于其正常位置进行定位。因此,"left:20" 会向元素的 left 位置添加 20 像素。
2.absolute(绝对定位):生成绝对定位的元素,相对于 static 定位以外的第一个父元素进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。
3.fixed (固定定位):生成绝对定位的元素,相对于浏览器窗口进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。
4.static (默认值):默认值。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。
5.inherit:规定应该从父元素继承 position 属性的值。
relative
元素会相对于它原来的位置偏移某个距离,元素原来所占的空间会被保留。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>定位的学习</title>
<style>
#d1{
width:400px;
height:400px;
background: red;
position:relative; /*为祖先元素设为相对定位,不设置top等,位置不发生变化*/
}
#d2{
width:200px;
height:200px;
background: yellow;
position:absolute;/*为子元素设置绝对位置,其位置会相对祖先元素d1变化*/
right:0;
top: 0;
}
#d3{
width:100px;
height:100px;
background: green;
position: absolute;/*位置会相对祖先元素d2变化*/
right:0;
top:0;
}
</style>
</head>
<body>
<div id="d1">
<div id="d2">
<div id="d3">
</div>
</div>
</div>
</body>
</html>
当子元素有俩个或多个时,子元素都会先根据其祖先元素的位置变化。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#d1{
width: 200px;
height: 200px;
background: red;
position:relative;
}
#d2{
width:100px;
height:100px;
background: yellow;
position: absolute;
top:3px;
left:3px;
}
#d3{
width:50px;
height:50px;
background: green;
position:absolute;
top:103px;
left:103px;
}
</style>
</head>
<body>
<div id="d1">
<div id="d2"></div>
<div id="d3"></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>left、right、top、bottom</title>
<style>
#d1{
width:200px;
height:200px;
background: red;
margin:0 auto;
margin-top:200px;
line-height: 200px;
text-align: center;
position: relative;
}
#d2{
width:100px;
height:100px;
position: absolute;
top:50px;
left:-90px;
background: green;
}
#d3{
width:100px;
height:100px;
position: absolute;
top:-80px;
left:50px;
background: blue;
}
#d4{
width:100px;
height:100px;
position: absolute;
top:50px;
right:-90px;
background: yellow;
}
#d5{
width:100px;
height:100px;
position: absolute;
bottom:-90px;
right:50px;
background: pink;
}
</style>
</head>
<body>
<div id="d1">
这是中间的div,祖先元素
<div id="d2"></div>
<div id="d3"></div>
<div id="d4"></div>
<div id="d5"></div>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#d1{
width:200px;
height: 200px;
background: red;
position: absolute;
left:3px;
top:3px;
z-index:2;
}
#d2{
width:200px;
height:200px;
background: yellow;
position:absolute;
left:50px;
top:50px;
z-index:1;
}
#d3{
width:200px;
height:200px;
background: blue;
position: absolute;
left:90px;
top:90px;
z-index:3;
}
</style>
</head>
<body>
<div id="d1"></div>
<div id="d2"></div>
<div id="d3"></div>
</body>
</html>