css - left,margin-left的使用场景有什么区别?

查看:121
本文介绍了css - left,margin-left的使用场景有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

left和margin-left的区别我都明白了,他们的使用条件有区别,但是在某些情景下,都可以用来定位,这时候该如何选择使用?

解决方案

left、right、top、bottom
是要跟定位position配合使用
而margin-left等没有定位也可以用
但是 你用margin-left等时要小心咯 各种坑@_@
主要是因为各个浏览器对margin解析不同 所以 会出现bug
大多数情况下 建议用padding O(∩_∩)O
以下代码展开讨论:(原谅我直接写了内联样式)
一、没有定位,直接设置margin-left

<div class="close" style="width: 200px;height:200px;background: red;">
   <div class="option" style="width: 100px;height: 100px;margin-left: 100px;background: blue;"></div>

执行结果:小盒子相对父亲红盒子向右偏移100px

二、没有定位,直接设置left

<div class="close" style="width: 200px;height:200px;background: red;">
   <div class="option" style="width: 100px;height: 100px;left: 100px;background: blue;"></div>
</div>

执行结果:小盒子保持原有位置

三、定位后 设置left

<div class="close" style="width: 200px;height:200px;background: red;position: relative">
   <div class="option" style="width: 100px;height: 100px;left: 100px;background: blue;position: absolute"></div>
</div>

执行结果:跟第一次一样

四、在定位基础上 设置margin-left

<div class="close" style="width: 200px;height:200px;background: red;position: relative">
   <div class="option" style="width: 100px;height: 100px;margin-left:20px;left: 100px;background: blue;position: absolute"></div>
</div>

执行结果:此时小盒子出了大盒子margin-left距离

这篇关于css - left,margin-left的使用场景有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆