开发者

why use negative margins?

Just looking at some CSS here, and I noticed:

.head{position开发者_运维问答:relative;overflow:hidden;margin:-30px 0 0 -25px;width:820px;padding:20px 25px 0 25px;background:url(/images/bkg.gif) 0 0 no-repeat;}

Why would you put -30 and -25px margins?


I started typing an answer, and then found a much better one here (Wayback Machine backup). Some salient points:

Negative margins:

  • are valid CSS
  • don't break page flow
  • have high levels of cross-browser compatibility (although if they break your link or floated image, then try adding position: relative; that should fix it)

Their effect on unfloated elements:

  • applying them to the top or left of an element "pulls" that element in the appropriate direction(s)
  • HOWEVER, applying them to the bottom or right of an element "pulls" immediately subsequent elements into them, making them overlap

Their effect on floated elements:

  • this is more complex and I can't summarise it better than the article. Have a play around in Firebug to get a feel for them.

There are some brilliant examples of negative margin use in that article (especially the 3-column layout! Magic. I've used a similar technique for page layout before.) The most common use for them I've found is just to move an element a small amount to correct its position, and to make one element overlap another for visual effect.


A lot of tricks and nice effects use negative margins:

Image Replacement Trick - when you want to use that particular font and you just can't tear away from it, image replacement is the trick. Uses negative margins to push out the regular font and replace it with the "picture" font.

Image Rollovers with borders - giving a negative margin to the image the same size in pixels as the border size will keep the image, and therefore the layout, from shifting on a rollover.

Center screen positioning - using negative margins the same dimension as the height and width of the object you want to center, you can center an object in the middle of the browser.


Negative margins can be helpful when you have other element "around" that you want to e.g. have a padding for all other elements. I use it very often, read here, why: http://www.simplebits.com/notebook/2005/05/23/negative.html


Actually i think there is an use case where negative margins are the only right thing to do:

You want an part of a box to extend over the whole parent, even over the padding. So instead of removing the padding of the parent element an apply it to all children exept for your special case, you give your special case a negative margin. Also no haggling with positioning. Works great and is very readable.

Example: http://codepen.io/anon/pen/DpHvu

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜