一、对自身的影响
当元素不存在width属性或者width: auto时,负值margin会增加元素的宽度,例子如下:
<div class="container">
<div class="box1">
没有设置宽度
</div>
</div>
.container{
margin:0 auto;
width: 200px;
border: 1px #ccc solid;
margin-bottom: 20px;
}
.box1{
margin-left: -20px;
}
可以看到box1增加了20px宽度,父元素".container"没有增宽(多出的宽度是边框宽度)。margin-left、margin-right都可以增加宽度。
那接下来我们看看margin-top和margin-bottom的情况:
#box {
width: 50%;
margin-bottom: -25px;
background-color: rgba(90, 243, 151, 0.8);
height: 50px;
}
<div id="box"> box </div>
<script src="http://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script>
<script>
var x = $('#box').height() console.log(x);
</script>
margin-top为负值不会增加高度,只会产生向上位移
margin-bottom为负值不会产生位移,会减少自身的供css读取的高度
二、对文档流的影响
设置margin-left: -40px;后:
设置margin-left: -40px;后:
可以看出,元素如果用了margin-left:-40px;元素会向左偏移20px,但和相对定位不同的是,在其后面的元素会补位,也就是后面的行内元素会紧贴在此元素的之后。总结,不脱离文档流不使用float的话,负margin元素是不会破坏页面的文档流。
三、对浮动元素的影响
<div class="fl" id="box1">box1</div>
<div class="fl" id="box2">box2</div>
<div class="fl" id="box3">box3</div>
.fl{
float: left;
width: 100px;
height: 100px;
}
#box1{background-color: rgba(255,255,0,.8);}
#box2{background-color: rgba(0,255,255,.8);}
#box3{background-color: rgba(255,0,0,.8);}
给三个div都加上margin-left: -20px;
可以看到三个盒子都先做移动了20px,box1向左移动20px,box2向左移动20px,所以我们只能看到60px的box1。
接下来只给box3添加margin-left:-200px;
box3覆盖了box1,显示在box2的前面。
总结:负margin会改变浮动元素的显示位置,即使我的元素写在DOM的后面,我也能让它显示在最前面。
四、对绝对定位元素的影响
<div class="absolute"></div>
.absolute{
position: absolute;
top:50%; left:50%;
height: 200px;
width: 200px;
background-color: #ccc;
margin-top: -100px;
margin-left: -100px;
}
对于绝对定位元素,负margin会基于其绝对定位坐标再偏移。
唯有的缺点就是你必须知道这个觉得定位元素宽度的和高度才能并设置负margin值使其居中浏览器窗口。
若不确定宽度和高度,可以用
transform: translate3d(-50%,-50%,0);
使用translate3d可以开启GPU加速,就不用cpu去从新计算所有点素位置,开启GPU加速后,GPU自动将这个元素放在一个新的“层”,直接偏移这个“层”来提高渲染速度。