margin:百分比,是相对于父元素的宽度
假设 给元素设置 margin:-40px
测试HTML
<main>
<div class="test">
元素的margin设置为负值
</div>
</main>
main {
width: 200px;
height: 200px;
border: 1px solid turquoise;
margin:200px;
}
.test {
border: 1px solid tomato;
width: 100px;
height: 100px;
margin: -40px;
opacity:0.7;
box-sizing: border-box;
}
一、基本情况
1、元素设置了宽度和高度 且 display:block
.test{
border: 1px solid tomato;
width: 100px;
height: 100px;
background-color: thistle;
opacity: 0.7;
margin: -40px;
box-sizing: border-box;
}
元素会向上偏移40px
元素会向左移动40px
元素宽度不变
像这样:
2、元素没有设置宽度 且 display:block
border: 1px solid tomato;
/* width: 100px; */
height: 100px;
background-color: thistle;
opacity: 0.7;
margin: -40px;
box-sizing: border-box;
元素会向上偏移40px
元素会向左偏移40px
此时元素的宽度改变了,等于父元素的宽度+40px*2
像这样:
margin为负值有哪些用处
position:absolute
+margin 负值 实现水平居中、垂直居中、水平垂直居中—适合宽度高度固定的
border: 1px solid tomato;
width: 100px;
height: 100px;
opacity: 0.7;
box-sizing: border-box;
background-color: thistle;
position: absolute;
top: 50%;
margin-top: -50px;
margin-top:-1px
解决border多1像素问题