Position的常用属性有:
- absolute:绝对定位。
相对于 static 定位以外的第一个父元素进行定位。 - relative:相对定位。
相对于其正常位置进行定位。 - fixed:固定定位。
相对于浏览器窗口进行定位。 - static:默认值,没有定位。
元素出现在正常的流中(忽略 top, bottom, left, right 或者 z-index 声明)。 - inherit:规定应该从父元素继承position属性的值。
- sticky:粘性定位,该定位基于用户滚动的位置。
它的行为就像 position:relative; 而当页面滚动超出目标区域时,它的表现就像 position:fixed;,它会固定在目标位置。
接下来,以最近所学知识用图文形式介绍一下相关属性的用法:
首先设置四个div ,如下所示:
<div id="first"> 第一块 </div>
<div id="second"> 第二块 </div>
<div id="third"> 第三块 </div>
<div id="forth"> 第四块 </div>
#first
{
width:800px;
height:100px;
background-color: orange;
}
#second
{
width:800px;
height:100px;
background-color: darkorchid;
}
#third
{
width:800px;
height:100px;
background-color: greenyellow;
}
#forth
{
width:800px;
height:100px;
background-color: dodgerblue;
}
效果图:
absolute的演示:
给第二个div添加absolute:
#second
{
width:800px;
height:100px;
position:absolute;
top:50px;
left:50px;
background-color: darkorchid;
}
效果图:
第二块的位置发生变化,是相对于第一块而言:距第一块顶部50px,左边50px;
即:absolute是对第一个父元素进行定位。
relative的演示:
给第二个div添加relative:
#second
{
width:800px;
height:100px;
position:relative;
top:50px;
left:50px;
background-color: darkorchid;
}
效果图:
第二块的位置发生变化,是相对于第二块原来的位置而言:距原来顶部50px,左边50px;
即:relative是对原先位置进行定位。
absolute与relative的具体区别演示及常用形式 :
先为第二个div设置一个父容器:
<div id="first"> 第一块 </div>
<div id="continer">
第二块的父亲
<div class="second"> 第二块 </div>
</div>
<div id="third"> 第三块 </div>
<div id="forth"> 第四块 </div>
1)对第二块设置absolute定位:(没有设定具体宽度)
(注意:必须也对父容器添加 position:absolute)
#first
{
width:800px;
height:100px;
background-color: orange;
}
#container
{
height:200px;
position:absolute;
background-color: #0A246A;
}
#container .second
{
height:100px;
position:absolute;
top:50px;
left:50px;
background-color: darkorchid;
}
#third
{
width:800px;
height:100px;
background-color: greenyellow;
}
#forth
{
width:800px;
height:100px;
background-color: dodgerblue;
}
在上面的代码中,可以看到:
1.并没有对 container 和 second 设置宽度,显示的是和文字同宽的大小;
2.second的位置是相对于父容器container发生的变化;
3.第三块和第四块其实应该具体说是被container所覆盖了一部分。
(可以巧妙利用该方法,使得第三块和第四块上移)
2)对第二块设置relative定位:(没有设定具体宽度)
(注意:必须对父容器添加 position:absolute)
#first
{
width:800px;
height:100px;
background-color: orange;
}
#container
{
height:200px;
position:absolute;
background-color: #0A246A;
}
#container .second
{
height:100px;
position:relative;
top:50px;
left:50px;
background-color: darkorchid;
}
#third
{
width:800px;
height:100px;
background-color: greenyellow;
}
#forth
{
width:800px;
height:100px;
background-color: dodgerblue;
}
在上面的代码中,可以看到:
1.没有对 container 和 second 设置宽度,second显示的是和父容器一样的宽度;
2.second的位置是相对于原来位置发生的变化;
为second设定具体宽度后,设定absolute 和 relative ,图像分别为:
可以看到:
1. absolute定位的子元素宽度不会影响父元素的宽
2. relative定位的子元素会撑大父元素。
总结absolute 和 relative的区别:
Absolution:
元素会脱离文档流,定位是相对于离它最近的且不是static定位的父元素而言,若该元素没有设置宽度,则宽度由元素里面的内容决定,且宽度不会影响父元素,定位为absolution后,原来的位置相当于是空的,下面的的元素会来占据。
Relative:
元素仍处于文档流中,定位是相对于原本自身的位置,若没有设置宽度,则宽度为父元素的宽度,该元素的大小会影响父元素的大小。
详细讲解,可以看下面的链接:
css , 定位看这里
fixed:
在有滚动条的情况下,fixed定位不会随滚动条移动而移动