在蓝色理想看到一篇帖子如何理解负边距,代码如下:
#mainer {
float:left;
width:100%;
margin-right:-300px;
background:silver;
}
#main {
margin-right:300px;
}
#sider {
float:right;
width:300px;
background:orange;
}
<div id="mainer">
<div id="main"><strong>main</strong></div>
</div>
<div id="sider"><strong>sider</strong></div>
实际效果如下:
margin值的解析规则是margin-left和margin-top的参考线为左边元素/上面元素的参考线,如果没有兄弟元素,就是以父元素的左内侧和上内侧为参考线(内侧即盒模型的content外侧)而margin-right和margin-bottom的参考线为元素本身的border右侧和border下侧为参考线。margin为正值会影响整个盒模型的大小即border以内的盒模型大小+margin值,如果margin为负值,则根据参考线向参考线外面位移。更详细的讲解请看由浅入深漫谈margin属性
写了一个小例子,代码如下:
.wrap{
width:400px;
padding:0;
height:400px;
background-color:#3C6;
border:1px solid #ccc;
margin:100px;
}
.box{ width:100px; height:100px;}
.box1{ margin:10px; background-color:#666; border:5px solid #09F;}
.box2{ margin:-10px;background-color:#666; border:5px solid #FC0;}
.box3{ background-color:#666; border:5px solid #000;}
<div class="wrap">
<div class="box box1"></div>
<div class="box box2"></div>
<div class="box box3"></div>
</div>
效果如下图:
顺便把margin值的叠加也总结一下:
叠加的结果是按照两者较大的margin值作为共同的margin值。示例代码如下:
.wrap{
width:600px;
height:600px;
background-color:#3C6;
margin:100px;
}
.box{ width:100px; height:100px;}
.box1{ margin:100px; background-color:#666; border:5px solid #09F;}
.box2{ margin:100px;background-color:#666; border:5px solid #FC0;}
.box3{ margin:100px 0;}
<div class="wrap">
<div class="box box1">box1</div>
<div class="box box2">box2</div>
<div class="box3"></div>
<div class="box box2">box2参考</div>
</div>
效果图如下: