一、position属性值讲解
- static
HTML元素的默认值,即没有定位,元素出现在正常的流中。静态定位的元素不会受到 top, bottom, left, right影响。
- fixed
元素的位置相对于浏览器窗口是固定位置,即使窗口是滚动的它也不会移动。
注意: 1,Fixed 定位在 IE7 和 IE8 下需要描述 !DOCTYPE 才能支持。
2,Fixed定位使元素的位置与文档流无关,因此不占据空间。
3,Fixed定位的元素和其他元素重叠。
- relative
1,相对定位元素的定位是相对其正常位置。
2,可以移动的相对定位元素的内容和相互重叠的元素,它原本所占的空间不会改变。
注意:相对定位元素经常被用来作为绝对定位元素的容器块。
- absolute
绝对定位,绝对定位的元素的位置,相对于最近的已定位父元素,
如果元素没有已定位的父元素,那么它的位置相对于<html>。
注意: 1,absolute定位使元素的位置与文档流无关,因此不占据空间。
2,定位的元素和其他元素重叠。
注意: 如果两个定位元素重叠,没有指定z - index,最后定位在HTML代码中的元素将被显示在最前面。
二、实例
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>测试position属性</title>
<style>
body{
border: 1px solid red;
}
._absolute{
position: absolute;
top:20px;
left: 20px;
width: 200px;
height: 200px;
color: red;
border: 1px solid red;
}
._relative{
position: relative;
top: 100px;
left: 100px;
width: 300px;
height: 300px;
color:blue;
border: 1px solid blue;
}
._static{
position: static;
top: 100px;
left: 10px;
color: green;
border: 1px solid green;
}
._fixed{
position: fixed;
left: 0;
top: 500px;
color: greenyellow;
border: 1px solid greenyellow;
}
</style>
</head>
<body>
<div class="_relative">
relative相对于body定位top: 100px;left: 100px;
<div class="_absolute">
absolute相对于_relative绝对定位,top:20px;left: 20px;
<div class="_static">
static无效果
<div class="_fixed">
fixed相对于浏览器定位,不跟随也没滚动
</div>
</div>
</div>
</div>
</body>
</html>