html定位详解
1.static(静态)定位,默认值,没有定位,元素出现在正常的流中(忽略left,right,top,bottom和z-index声明)
2.relative(相对)定位,可以通过设置left,right,top,bottom来设定其相对原来位置的偏移量,但元素本身并没有脱离普通流,也就是说元素原本所在位置依然被其占着,其余元素并不能移到他原本所在位置,相当于原来位置没有东西了但还是被占着,如下代码:
<html>
<head>
<title></title>
<style>
*{
margin:0;
padding:0;
}
.red{
background:red;
width:100px;
height:100px;
position:relative;
left:20px;
top:20px;
}
.blue{
background:blue;
width:100px;
height:100px;
}
</style>
</head>
<body>
<div class='red'></div>
<div class='blue'></div>
</body>
</html>
在页面中显示为:
3.absolute(绝对)定位,元素会脱离普通流,使用left,right,top,bottom等属性相对其最接近的一个并有定位设置(并不一定是relative定位,只要是非static定位即可)的父元素进行绝对定位,如果不存在这样的父对象,则相对于body元素定位。如下代码:
<html>
<head>
<title></title>
<style>
*{
margin:0;
padding:0;
}
.black{
margin-top:200px;
background:black;
width:200px;
height:200px;
}
.red{
background:red;
width:100px;
height:100px;
position:absolute;
left:20px;
top:20px;
}
.blue{
background:blue;
width:100px;
height:100px;
position:absolute;
left:20px;
top:20px;
}
</style>
</head>
<body>
<div class='black'>
<div class='red'>
<div class='blue'></div>
</div>
</div>
</body>
</html>
在页面中显示为:
4.fixed(固定)定位,元素会脱离普通流,可以通过设置left,right,top,bottom来相对于窗口定位。
我们可以通过设置定位元素的z-index值来规定其在页面中的显示层级,注意,z-index属性仅对非static定位元素有效