I dislike negative margins in CSS
There, I've said it. This seems to be a topic that comes up in the office from time to time, using negative margins in css for page layout.
I'll concede there may be times when it seems the only way to get the look you're after but so far none of the sites I've created from scratch have needed to use negative margins (or padding for that matter).
Why the beef with negative margins and padding?
Semantics and maintainability
Ok, semantics may not be the right word to use but bear with me...
I (being English) read pages left to right, top to bottom. When I look at at a page and want to adjust the position of an element I will look for it in that place in the html code. ie I would expect a top banner div to appear very early in the HTML, not at the bottom then styled to the top with negative margins.
Use the fact the browsers display elements in a flow, one after another.
Maintainance is the biggie for me, above is a very simplistic example, but imagine the situation when you have a number of nested elements with varying amounts of margins and padding both sides of zero. Trying to work out what impacts what is a maintenance nightmare.
Without exception, so far everytime I've come across a negative margin or padding in an application it has been removable by refactoring the CSS into simpler, cleaner classes and often fewer classes.
It only seems to be used when there are too many rules affecting how an element is positioned on the page. Instead of wildly throwing in a dirty negative margin to fix a layout, go back to the box model and work out why your element looks too far to the right. Maybe a little too much margin/padding on the element to the left.
Have a look at your other elements - are they positioned absolutely when they don't need to be? Let the content flow.
Negative margins are a valid part of the CSS recommendation from W3C however, so calling them a hack is a bit unfair but in my experience negative margins are only used as a quick fix instead of cleaning up the code properly.
Not always bad
After all that I concede there may be times when the desired result can only be achieved with negative margins and doing so doesn't introduce maintainability issues. Negative margins can be used to create deliberate overlaps of elements for example (sibling breaking out of parent element).
I've not met one of those situations yet, but I don't claim to know everything!
Some further reading
- http://www.bennadel.com/blog/1174-Negative-CSS-Margins-Are-Not-Cool.htm - interesting discussion in the comments for the page
- http://www.search-this.com/2007/08/01/the-positive-side-of-negative-margins/ - some thoughts on when negative margins are a good thing (there are valid uses occasionally it seems!)