left和margin-left的区别

一、在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,绿线框的位置:

即:left是相对它最近的设置了position的父元素进行定位的。如何不设置红框的position,那么绿框就是相对蓝框进行设置left。

 

二、设置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,绿线框的位置:

 

参考:https://blog.csdn.net/tomatozq/article/details/7178144

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值