一、可能的值
值 | 描述 |
---|---|
static |
默认值 。没有定位,元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。 |
absolute | 生成绝对定位的元素,相对于static 定位以外的第一个父元素 进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。 |
fixed | 生成绝对定位的元素,相对于浏览器窗口 进行定位。元素的位置通过 "left", "top", "right" 以及 "bottom" 属性进行规定。 |
relative | 生成相对定位的元素,相对于其正常位置进行定位。因此,"left:20" 会向元素的 LEFT 位置添加 20 像素。 |
inherit | 规定应该从父元素继承 position 属性的值。 |
二、实例
1. 绝对定位
<div class="first"></div>
<div class="second"></div>
<style type="text/css">
.first {
background: red;
width: 100px;
height: 100px;
}
.second {
background: blue;
width: 100px;
height: 100px;
}
</style>
我们可以看到正常的两个颜色块,下面我们对元素采用absolute
绝对定位。
<div class="first"></div>
<div class="second"></div>
<div class="posi"></div>
<style type="text/css">
.first {
background: red;
width: 100px;
height: 100px;
position: absolute;
}
.second {
background: blue;
width: 100px;
height: 100px;
}
.posi {
background: green;
width: 100px;
height: 100px;
}
</style>
现在三个块,但是我们实际上能看到的只有两个了。因为first
把后面的second
块盖住了。如果我们想要second
不被遮住,可以给firs
t加一个z-index
的属性,默认的z-index
是0
,那我们让它小于
0就行。或者我们给它加入一行文字。
<div class="first"></div>
<p>加入一行文字看看效果</p>
<div class="second"></div>
<div class="posi"></div>
<style type="text/css">
.first {
background: red;
width: 100px;
height: 100px;
position: absolute;
}
.second {
background: blue;
width: 100px;
height: 100px;
}
.posi {
background: green;
width: 100px;
height: 100px;
}
</style>
这时可以看到蓝色块露出来了一截,因为文字块
成为正常定位的第一个元素,second
是紧接在它后面,所以就能够看到一部分蓝色块了。
2.相对定位
<div class="first"></div>
<p>加入一行文字看看效果</p>
<div class="second"></div>
<div class="posi"></div>
<style type="text/css">
.first {
background: red;
width: 100px;
height: 100px;
position: absolute;
}
.second {
background: blue;
width: 100px;
height: 100px;
position:relative;
left:60px
}
.posi {
background: green;
width: 100px;
height: 100px;
}
</style>
我们可以看到,relative
定位,是相对于它自己本来应该在的位置,再进行相对定位。
网友评论