现在的位置: 首页 > 综合 > 正文

css中margin-left与left的区别

2013年04月05日 ⁄ 综合 ⁄ 共 1291字 ⁄ 字号 评论关闭

研究下拉菜单和弹出菜单时比较所得:
1.直接在css中设置left生效的前提是必须设置父容器position:absolute或relative,如果不设置则会显示为最近一个定位的父对象左边相关的位置:
测试代码:

	<div style="position:relative;top:100px;left:100px;border:1px solid blue;width:100px;height:100px;">
	<div id="outer" style="position:relative;margin-top:25px;margin-left:25px;width:50px;height:50px;border:1px solid red;">
		<div id="inner" style="position:absolute;left:15px;top:15px;width:25px;height:25px;border:1px solid green;"></div>
	</div>
	</div>

测试效果:
不设置红线框的position,设置蓝线框的position,绿线框的位置:


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

2.设置margin-left则只会出现在父对象的左边的相对位置,不考虑是否设置了position。
测试代码:

	<div style="position:relative;top:100px;left:100px;border:1px solid blue;width:100px;height:100px;">
	<div id="outer" style="position:relative;margin-top:25px;margin-left:25px;width:50px;height:50px;border:1px solid red;">
		<div id="inner" style="position:absolute;margin-left:15px;margin-top:15px;width:25px;height:25px;border:1px solid green;"></div>
	</div>
	</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

抱歉!评论已关闭.