【JavaScript】div+css定位position详解

来源:互联网 发布:北京大学远程网络教育 编辑:程序博客网 时间:2024/06/01 09:49


  1、div+css中的定位position 最主要的两个属性:absolute(绝对定位)、relative(相对定位)

   (1)absolute(绝对定位),位置将依据浏览器左上角开始计算。 绝对定位使元素脱离文档流,因此不占据空间。

   (2)relative(相对定位),定位是相对的,那他是相对于什么呢?参照物是什么?

   看代码:

<span style="font-size:18px;"><style type="text/css"> #left{background:#cccccc;width:200px;height:200px;float:left;} #center{background:#eee;width:200px;height:200px;float:left;} #right{background:#666666;width:200px;height:200px;float:left;}</style><div id="left"></div><div id="center"></div><div id="right"></div></span>
  效果:

     

  2、relative(相对定位),给中间的div增加定位属性:position:relative; top:10px; left:10px;

  代码:

<span style="font-size:18px;"><style type="text/css"> #left{background:#cccccc;width:200px;height:200px;float:left;} #center{background:#eee;width:200px;height:200px;float:left;position:relation;top:<span style="font-family:KaiTi_GB2312;">1</span>0px;left:<span style="font-family:KaiTi_GB2312;">1</span>0px;} #right{background:#666666;width:200px;height:200px;float:left;}</style><div id="left"></div><div id="center"></div><div id="right"></div></span>
  效果:

     

  结果:很明显它现在移动的参照物就是它原来所占据的位置

  注意:位置属性 top、 right 、left 、bottom 只能引用相邻的两个边,不能只用上下,或者只用左右。

  3、absolute(绝对定位),给中间的div增加定位属性:position:absolute; top:30px; left:30px;

  代码:

<span style="font-size:18px;"><style type="text/css"> #left{background:#cccccc;width:200px;height:200px;float:left;} #center{background:#eee;width:200px;height:200px;float:left;position:absolute;top:30px;left:30px;} #right{background:#666666;width:200px;height:200px;float:left;}</style></span>

  效果:

     

  结果:

  发现中间的div脱离了文档流,右侧的和左侧div挨着了,现在中间的div的位置是从浏览器的左上角开始计算位置即向下移动30像素,向右移动30像素。现在就涉及到一个层级的关系,设置div的z-index属性,数值越大的,层显示在最上边。

   想要了解更多的小伙伴们可以点击这里:

  CSS 相对|绝对(relative/absolute)定位系列(一)


0 0
原创粉丝点击