一、首先是对自身的影响
1.margin-left,margin-right会增加元素自身宽度。
<head>
<style>
.container{
width:400px;
margin:0 auto;
background-color: black;
}
.box {
width: auto;
height: 40px;
margin-left:-40px;
background-color: pink;
}
</style>
</head>
<body>
<div class="container">
<div class="box">
m
</div>
</div>
</body>
当自身元素宽度未设置或width:auto时,margin为负值会增加元素自身的宽度;
如图:(width:auto时)
如图:(width:auto时且设置了margin-left:-40px)
2.margin-top,margin-bottom。
①margin-top:-40px 不会改变元素自身宽高,而是让元素上移。
<head>
<style>
.container{
width:400px;
height:40px;
margin-top:-40px;
background-color: black;
}
</style>
</head>
<body>
<div class="container">
</div>
</body>
效果如图:
②margin-bottom:-40px未在元素渲染方面正常。
二、对浮动元素的影响
<style>
.box1,.box2,.box3{
width:100px;
height:100px;
float: left;
}
.box1{
background-color: red;
}
.box2{
background-color: yellow;
}
.box3{
background-color:blue;
margin-left:-200px;
}
</style>
<body>
<div class="box1">盒子1</div>
<div class="box2">盒子2</div>
<div class="box3">盒子3</div>
</body>
首先不添加负的margin值:
然后给每个盒子添加margin-left:-20px:
可以看到的是:每个盒子产生了位移都向左偏移了20px,且后设置margin-left为负值的元素会覆盖在先设置margin-left为负值的的元素上面。
盒子1,盒子2不添加margin值,只给盒子3加上margin-left:-100px:
可以看到盒子3完全覆盖掉了盒子1的位置。
总结:负margin会改变浮动元素的显示位置,即使元素写在后面,也可以用负margin值
让它显示在最前面。
三、对绝对定位元素的影响
<style>
.box{
width:200px;
height:200px;
position: absolute;
top:50%;
left:50%;
/* margin-left:-100px;
margin-top:-100px; */
background-color:black;
}
</style>
<body>
<div class="box"></div>
</body>
不添加负的margin值:
添加了margin-left:-100px;margin-top:-100px后:
可以看出元素相对于其绝对定位的坐标,进行了偏移。