先给出例子,看HTML
<div class="box">
<div class="box-1">
box-1
</div>
<div class="box-2">
box-2
</div>
<div class="box-4">
box-4
</div>
</div>
写出CSS
.box-1{
float:left;
width:300px;
height:100px;
background:#f00;
}
.box-2{
float:left;
width:300px;
margin-right:-300px;
background:#369;
}
.box-4{
float:left;
width:300px;
background:#ddd
}
没错,是那margin-right:-300px惹的祸,它把它对下一元素的参考线为-300px,所以.box-4才会覆盖在box-2上面。我们看看margin的基本特性
margin 属性包括 margin-top, margin-right, margin-bottom, margin-left, margin,可以用来设置 box 的 margin area。属性 margin 可以用来同时设置 box 的四边外边距,而其他的 margin 属性只能设置其自各的外边距。
margin 属性可以应用于几乎所有的元素,除了表格显示类型(不包括 table-caption, table and inline-table)的元素,而且垂直外边距对非置换内联元素(non-replaced inline element)不起作用。
或许有朋友对非置换元素(non-replaced element)有点疑惑,稍微帮助大家理解一下。非置换元素,W3C 中没有给出明确的定义,但我们从字面可以理解到,非置换元素对应着置换元素(replaced element),也就是说我们搞懂了置换元素的含义,就懂了非置换元素。置换元素,W3C中给出了定义:
“An element that is outside the scope of the CSS formatter, such as an image, embedded document, or applet”
从定义中我们可以理解到,置换元素(replaced element)主要是指 img, input, textarea, select, object 等这类默认就有 CSS 格式化外表范围的元素。进而可知,非置换元素(non-replaced element)就是除了 img, input, textarea, select, object 等置换元素以外的元素。
margin 始终是透明的。
仔细看下面的图,就很好理解了。

让我们醍醐灌顶
增加一个box-3,使用margin-left:300px把margin-right:-300px抵消掉
.box-3{
float:left;
width:0px;
white-space:nowrap;
margin:0 0 0 300px;
overflow:hidden;
background:#fe8;
}
在box-2下增加box-3
<div class="box-3">
box-3
</div>
并不推荐这么做,很显然我的结构有问题。现只是作为例子。
(注:本文图片,定义直接copy译飞的由浅入深漫谈margin属性)

