why use negative margins?

前端 未结 4 983
天命终不由人
天命终不由人 2020-12-18 15:35

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:         


        
4条回答
  •  渐次进展
    2020-12-18 16:23

    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.

提交回复
热议问题