2.7定位
定位方式有:
static:静态的定位(默认)
无定位,元素正常出现了流中,不受left、right、top、bottom影响
fixed:固定定位
relative:相对定位
absolute:绝对定位
<style type="text/css">
#div1{
width: 200px;
height: 200px;
background-color: red;
}
#div2{
width: 200px;
height: 200px;
background-color:greenyellow;
}
</style>
显示效果为:
代码:<style type="text/css">
#div1{
width: 200px;
height: 200px;
background-color: red;
position: fixed;
left:30px;
top: 20px;
}
#div2{
width: 200px;
height: 200px;
background-color:greenyellow;
}
</style>
显示效果为:
从结果可以看出:fix定位会将元素从流中“摘”出来单独进行定位,其定位取决于left、top。
重新定位之后可能会出现重叠,通过z-index可以调整其顺序,但是定位z-index无效。
相对定位:
relative
代码如下:
<style type="text/css">
#div1{
width: 200px;
height: 200px;
background-color: rgba(255,0,0,1);
}
#div2{
width: 200px;
height: 200px;
background-color:greenyellow;
position:relative;
top: 20px;
left:30px;
}
#div3{
width: 100px;
height: 100px;
background-color: blue;
}
</style>
结果如下:
从结果可以看出,相对定位是从原有位置进行位移,但是并不影响后续位置。
绝对定位:
Absolute
代码如下:
<style type="text/css">
#div1{
width: 200px;
height: 200px;
background-color: rgba(255,0,0,1);
}
#div2{
width: 200px;
height: 200px;
background-color:greenyellow;
position:fixed;
top: 20px;
left:30px;
}
#div3{
width: 100px;
height: 100px;
background-color: blue;
}
</style>
结果如下:
从结果可以看出:绝对定位的元素将从流中被“摘”出来,依靠left top属性进行定位。
与fixed类似,但是参照物不同
fixed参照根元素(html)
absolute参照父容器