Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
798 views
in Technique[技术] by (71.8m points)

css - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...