tags:

views:

169

answers:

4

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?

+8  A: 

I started typing an answer, and then found a much better one here. 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.

Robert Grant
You could summarize the contents of that link in your answer. That would get you more votes, and help those who just want a quick answer.
Martinho Fernandes
That is a very nice article.
Summarised as per instruction :)
Robert Grant
A: 

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

Dimitri Wetzel
+1  A: 

Because CSS layouts are 90% tricks to make things work and 10% logic. I'll face downvotes courageously :D

kemp
Don't blame CSS! Blame browsers that refuse to adhere to the standards set by CSS ;-)
Duroth
+1 for the browser silliness fact. What's so hard about coding your browser to work with CSS? Still want browser wars?
tahdhaze09
"What's so hard about coding your browser to work with CSS" - ever seen the CSS spec? :)
Robert Grant
A: 

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.

tahdhaze09