position定位 left和offsetLeft的区别

1.当该对象的positionrelative时,根据自己最初的位置进行定位,不受父级的定位影响。

例:

.a{width: 200px;height: 200px;border: 1px solid red;margin-top: 100px;margin-left:100px;position:absolute;}
.b{width:100px;height:100px;position:relative;background-color:pink;top:50px;left:50px;}

2.当该对象的positionfixed时,根据窗口的视图进行定位,不受父级的定位影响。

例:

.a{width: 200px;height: 200px;border: 1px solid red;margin-top: 100px;margin-left:100px;position:absolute;}
.b{width:100px;height:100px;position:fixed;background-color:pink;top:50px;left:50px;}

3.position:sticky 粘性定位,相对于父级和BFC进行定位。类似fixed定位和relative的混合。只有指定了top、left 、right、bottom  其中的一个值才能生效转成粘性定位,否则一直为relative定位。

例如:.b{position:sticky;top:10px;} 当b相对父级的位置小于等于10px的时候,b会转成{position:fixed;top:10px;},否则为{position:relative;top:10px;}

 

4.当该对象的定位position为absoluteleft是相对于拥有定位属性(position的值为默认值"static"时除外)的父级对象的左边距。

例1:当父级a的positionrelative、absolute或者fixed时,b都根据a进行定位。

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="utf-8">
 5 <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
 6 <title></title>
 7 <style>
 8     .a{width: 200px;height: 200px;border: 1px solid red;margin-top: 100px;margin-left:100px;position:relative;}
 9     .b{width:100px;height: 100px;position:absolute;background-color:pink;top:0;left:0;}
10 </style>
11 </head>
12 <body>
13     <div class="a">
14         <div class="b"></div>
15     </div>
16 </body>
17 </html>

例2:当a没有设定位(position)或者positionstatic时,b根据浏览器的左上角定位。

.a{width: 200px;height: 200px;border: 1px solid red;margin-top: 100px;margin-left:100px;position:static;}
.b{width:100px;height: 100px;position:absolute;top:0;left:0;}

       

 

 

offsetLeft :

相对于父级的左边距。

  

        

 

posted @ 2016-05-27 13:54  四国诸葛不亮  阅读(627)  评论(0编辑  收藏  举报