使用负值margin


什么是负值margin

简单点说就是

content{margin-right:-10px;}

  • 因为负值是CSS2中定义的,W3C特意加了一句Negative values for margin properties are allowed,…这里
  • 兼容性很强,所有现代浏览器都支持【IE6也在大部分情况下都支持】
  • 在margin属性中一共有两类参考线,top和left的参考线属于一类,right和bottom的参考线属于另一类。top和left是以外元素为参考,right和bottom是以元素本身为参考。当margin四个值都为正数值的话,那么margin按照正常逻辑同周围元素产生边距。当元素margin的top和left是负值时会引起元素的向上或向左位置移动。而当元素margin的bottom和right是负值时会影响右边和下边相邻元素的参考线。

使用负值margin

margin-motion

static元素就是遵从Normal flow布局的元素

  1. 当static元素在上/左方向设置负值margin以后,该元素就会被拉到相应位置,例如,

    /* 把元素向上移动10px */
    #div1{margin-top:-10px;}

  2. 当static元素在下/右方向设置的时候,则不会移动元素,只会把后面的元素拉向该元素里面,并且会重叠覆盖。
    /* #div1下面的所有元素都被向上移动10px,#div1本身不移动 */
    #div1{margin-bottom:-10px;}
  3. 如果没有设置宽度,在左右方向设置负值margin,会把该元素向左右两个方向拉伸,跟padding类似。
    常用来做[一像素的模拟按钮][4]

IE6 中的bug

当负值margin用在float元素上时,在IE6中可能会:

  • 链接不能点击
  • 文字不容易选中
  • Tab键不能选中链接
  • 一些内容会消失

解决方法就是加上position:relative;

一些参考资料:
[1]: http://www.w3.org/TR/CSS2/box.html#margin-properties “W3C CSS2 margin定义”
[2]: http://media.smashingmagazine.com/wp-content/uploads/images/css-negative-margins/margin-motion.gif  “NEGATIVE MARGINS ON STATIC ELEMENTS”
[3]: http://www.w3.org/TR/CSS2/visuren.html#positioning-scheme “W3C CSS2 Positioning”
[4]: http://jsbin.com/ayomas/2/edit “负值margin模拟圆角按钮”
[5]: http://www.hicss.net/i-know-you-do-not-know-the-negative-margin/ “我知道你不知道的负Margin”
[6]: http://www.hicss.net/do-not-tell-me-you-understand-margin/ “不要告诉我你懂margin”
[7]: http://www.planabc.net/2007/03/18/css_attribute_margin/ “由浅入深漫谈margin属性”

[8]: http://coding.smashingmagazine.com/2009/07/27/the-definitive-guide-to-using-negative-margins/ “The Definitive Guide to Using Negative Margins”