css中margin-left与left的区别

来源:互联网 发布:炫酷的表白js特效代码 编辑:程序博客网 时间:2024/05/16 05:41
研究下拉菜单和弹出菜单时比较所得:
1.直接在css中设置left生效的前提是必须设置父容器position:absolute或relative,如果不设置则会显示为最近一个定位的父对象左边相关的位置:
测试代码:
[html] view plaincopy
  1. <div style="position:relative;top:100px;left:100px;border:1px solid blue;width:100px;height:100px;">  
  2. <div id="outer" style="position:relative;margin-top:25px;margin-left:25px;width:50px;height:50px;border:1px solid red;">  
  3.     <div id="inner" style="position:absolute;left:15px;top:15px;width:25px;height:25px;border:1px solid green;"></div>  
  4. </div>  
  5. </div>  
测试效果:
不设置红线框的position,设置蓝线框的position,绿线框的位置:


设置红线框的position,设置蓝线框的position,绿线框的位置:


2.设置margin-left则只会出现在父对象的左边的相对位置,不考虑是否设置了position。
测试代码:
[html] view plaincopy
  1. <div style="position:relative;top:100px;left:100px;border:1px solid blue;width:100px;height:100px;">  
  2. <div id="outer" style="position:relative;margin-top:25px;margin-left:25px;width:50px;height:50px;border:1px solid red;">  
  3.     <div id="inner" style="position:absolute;margin-left:15px;margin-top:15px;width:25px;height:25px;border:1px solid green;"></div>  
  4. </div>  
  5. </div>  
不设置红线框的position,设置蓝线框的position,绿线框的位置:


设置红线框的position,设置蓝线框的position,绿线框的位置:


3.设置margin-right无法起到将element定位到右边相距XX位置,但设置right可以。
测试代码:
<div style="position:relative;width:98px;height:63px;background-image:url('images/pic.png');margin-left:100px;margin-top:300px;">
<img src="images/delete.gif" style="position:absolute;top:-10px;right:-5px;"/>
</div>


测试效果:
设置margin-right


设置right

0 0
原创粉丝点击