咱们最经常使用的的就是 absolute 和 relative 两种方式,因此主要讨论着二者的区别。css
相对定位咱们主要是要知道相对于谁来进行偏移的?其实相对定位是相对于元素本身的自己的位置,咱们来看一下例子: html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <style type="text/css"> html body { margin: 0px; padding: 0px; } #parent { width: 200px; height: 200px; border: solid 5px black; padding: 0px; position: relative; background-color: green; top: 15px; left: 15px; } #sub1 { width: 100px; height: 100px; background-color: blue; } #sub2 { width: 100px; height: 100px; background-color: red; } </style> </head> <body> <div id="parent"> <div id="sub1"> </div> <div id="sub2"> </div> </div> </body> </html>
这是一个嵌套的DIV,一个父Div Parent, 包含两个子DIV Sub1 和 Sub2,因为两个子DIV没有设置任何Position属性,它们处于它们应当的位置。默认位置以下图:浏览器
当咱们修改一下Div Sub1 的样式: post
#sub1 { width: 100px; height: 100px; background-color: blue; position: relative; top: 15px; left: 15px; }
结果以下图:咱们会发现Sub1进行了偏移,并不影响Sub2的位置,同时遮盖住了Sub2,切记偏移并非相对于 Div Parent的,而是相对于Sub1 原有的位置。url
若是咱们把Sub1 的同级Div Sub2 也设置一个相对位置,会产生什么结果?咱们来看一下。spa
#sub2 { width: 100px; height: 100px; background-color: red; position: relative; top: 10px; left: 10px; }
结果以下图:3d
Sub2也根据原有位置进行了偏移,同时遮盖住了Sub1,也不会影响Sub1的位置。相对定位比较容易理解,咱们再来看一下绝对定位Absolute。code
绝对定位在使用当中比较容易出错的,有几个须要注意的地方,将上面的代码还原,咱们为Sub1 增长一个绝对定位。xml
#sub1 { width: 100px; height: 100px; background-color: blue; position: absolute; top: 15px; left: 15px; }
结果以下:htm
咱们发现,因为咱们对Sub1进行了绝对定位,Sub1的位置发生了偏移,而同级Div Sub2,则占据了Sub1的位置,而且Sub1遮挡了Sub2.
下面,把Sub2 也增长绝对定位:
#sub2 { width: 100px; height: 100px; background-color: red; position: absolute; top: 10px; left: 10px; }
结果以下:
咱们会发现,Sub2 也进行了偏移,而且遮盖住了Sub1。
这时候,咱们会发现问题,两个子Div 都设置了 绝对定位,他们是相对于哪一个元素发生了偏移呢?
这分两种状况:
一、若是Sub1 的父元素或者祖父元素,设置了Position属性,而且属性值为 absolute 或 relative的时候,那么子元素相对于父元素来进行定位。好比咱们例子中最外层Div Parent设置了相对定位属性,所以Sub1 和 Sub2 两个Div 就根据 Div Parent 来进行定位。可是根据Parent那个定位点进行定位呢?答案是:若是parent设定了margin,border,padding等属性,那么这个定位点将忽略padding,将会从padding开始的地方(即只从padding的左上角开始)进行定位。
二、若是sub1不存在一个有着position属性的父对象,那么那就会以body为定位对象,按照浏览器的窗口进行定位。
咱们将例子中的Parent 的Position 属性删除,再来看一下结果:
因为两个子div没有找到有Position属性的父元素,则以Body进行定位,因为图片缘由,请不要误觉得是相对于Parent的。
fixed是一种特殊的absolute,fixed老是以body为定位对象的,按照浏览器的窗口进行定位。咱们将代码还原到最初状态,Sub1 增长absolute定位方式,而Sub2 增长fixed定位方式:
#sub1 { width: 100px; height: 100px; background-color: blue; position: absolute; top: 15px; left: 15px; } #sub2 { width: 100px; height: 100px; background-color: red; position: fixed; top: 5px; left: 5px; }
结果以下:
会发现Sub2 始终以body 进行定位,而Sub1因为发现Parent 有position属性relative,则根据父元素进行定位偏移。
注意fixed 在IE 低版本中式不支持的,包括IE6
至于 static 和 inherit 两种定位,项目中不多用到,static 就是Position属性的默认值,通常不设置position属性时,会按照正常的文档流进行排列。这里就不在赘述。