Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
I am the chief technical officer at InVision App, Inc - a prototyping and collaboration platform for designers, built by designers. I also rock out in JavaScript and ColdFusion 24x7.
Meanwhile on Twitter
Loading latest tweet...
Ben Nadel at cf.Objective() 2009 (Minneapolis, MN) with:

Negative CSS Margins Are Not Cool

By Ben Nadel on
Tags: HTML / CSS

This is a bit of blanket statement, so clearly it is not going to be true all of the time; but, it is my very strong opinion that if you have any negative margins on an XHTML element, then the code is not cool. I know that every now and then I come out with these very black and white statements like this and get heat for it, but I just feel this so strongly in my gut. Plus, I have spent too much time filling in on projects where, time and time again, negative margins have been breaking layouts across browsers and on pages with dynamic content. It's driving me a little bananas.

Now, before you get all steamed up and throw the tomatoes, take a moment and think about it. A negative margin? Shouldn't that very idea seem like a physical impossibility? How can an object have a negative margin? Yes, we all know what it does at a practical CSS level, but the very idea of it feels so wrong. Shouldn't your code feel right? Shouldn't you be proud of it and want to take it home and have it meet your mother and then let it sleep in another room because even though you love the code so much you're at your mother's house and it's her house, her rules?

Instead of using a negative margin, maybe try floating an element? Or perhaps positioning it absolutely to its parent? Before you even consider a negative margin, please consider what would happen if other elements on the page changed height or width. My guess is that your negative margin depends way too much on other parts of the page in a way that is not necessary.

There are times when negative margins can add nice little accents for design such as a slightly offset image or icon. But, if you are using a negative margin as an integral part of your page layouts, you might want to try and rework the code.


 
 
 

 
Keep Your Negative-Margin Fingers Off My <BODY> And Out Of My Box Model  
 
 
 
Tweet This Deep thoughts by @BenNadel - Negative CSS Margins Are Not Cool Thanks my man — you rock the party that rocks the body!


Reader Comments

Some good comments. The only time I've used negative margins are when I couldn't get one of the major browsers to behave the same way as the others. But I am very far from a CSS expert, so I'm sure there are better ways to solve the problem...

Reply to this Comment

There are plenty of situations where negative margins are appropriate. Why is a negative margin any worse than a negative value on a position, or text-indent, for example? Negative margins affect elements that occur after them in the document flow in a unique way that floats or absolute positioning can't match. Only use positive margins if you like, but you'll be limiting the tools at your disposal to create effective websites.

Reply to this Comment

There are plenty of situations where negative margins are appropriate. Why is a negative margin any worse than a negative value on a position, or text-indent, for example? Negative margins affect elements that occur after them in the document flow in a unique way that floats or absolute positioning can't match. Only use positive margins if you like, but you'll be limiting the tools at your disposal to create effective websites.

Reply to this Comment

Concrete example of a good use for a negative margin:

Take a blank piece of unlined paper. Skip down a few inches, then write on it -- a few lines, then a few paragraphs. Add a quick bulleted list. Draw a box that represents an image.

Now look at what you've done. Odds are, unless you've got some deep-seated psychological issues, you didn't start at the extreme left edge of the page, but indented a bit. Similarly, your writing probably doesn't hit the far right edge of the page, but again has some space. Let's call it 0.5 inch.

But is it margin or padding? It doesn't make sense to have the paragraphs and lists and images, and all of the other child elements you might have, worrying about adding in a 0.5 inch margin, so instead we just add the padding to the body:

body { padding: 2in 0.5in 0.5in 0.5in; }

Yes, you could also technically do it this way, but it's just silly:

body > * { margin-left: 0.5in; margin-right: 0.5in; }

Now go back and give the page a nice big title, such as "OMG Best Web Page EVAR". Beneath that title, draw a line. But here's the trick: draw the line from the extreme left edge of the page to the extreme right edge of the page. Take a crayon or highlighter and color in the background for the top part of your page that has the title.

How do we do that in CSS? The body already has padding, but we want the color to go to the edge of the page, not be some colored-in square with a half-inch of white all around it.

#title {
margin: -2in -0.5in 0.25in -0.5in;
padding: 0.25in;
border-bottom: thin solid maroon;
color: maroon;
font-size: 120%;
background-color: yellow;
font-weight: bold;
}

See?

The other advantage of doing it this way is that the box for the content has "sane" coordinates that start where the content starts, and not at the extreme left/right edges of the page. That is, if I want to indent something another 0.5in, I don't have to remember that I've already got 0.5in and so set my margin to 1.0in, and then work some magic to set nested elements back to 0.5in so that they aren't all at 1.0in.

Down that path lies madness.

Reply to this Comment

But then what if you add more elements to the page that you want to start from the left of the page and go all the way across? And what if you edit the body tag padding? You then have to go back in and manipulate the negative values to match the changes in the body tag.

Reply to this Comment

@Richard,

To me, negative margins are very different than a negative position. Position coordinates are just relative to a given 0,0 axis. Some of those coordinates are going to be negative. Negative values, in an of themselves are not bad. I just think with margins, they should be used with extreme caution.

@Rick,

I see what you are saying. I have never done that personally, but I see where it cold be useful. Let me ask you this, could the same thing be done with:

#title {
position: relative ;
left: -.5in ;
top: -2in ;
padding: .25in 1in .25in .25in ;
}

... the numbers might not add up exactly, but I think the same effect can be achieved via relative positioning. The problem is that to get the full width, you have to add padding (unless you know the width of the content area, then you can just set the explicit width).

I believe that a negative relative position will work the same way as a negative margin, but will make more sense from a box-model standpoint.

Reply to this Comment

Gareth- It has been my experience that the vast majority of the time any content I add to a page will be within the borders, and only a few rare exceptions will break out of their box into the margins. Thus, it's easier to not have to remember for most new content, than it is to have to remember every time I start using something new on my page.

And, yes, if I decide that I want a 0.75in margin around the page instead of a 0.5in margin, I do have to remember to change the elements that break through that margin. But again, the whole point here is that there are fewer cases where elements break through the margin than there are that do not. Thus, fewer places to change.

Ben- Relative positioning does, I agree, make more sense from a box model standpoint. However, in practice, I've found that it has been poorly implemented by browsers enough times as to make it almost useless. Give it another 2-5 years, and I'll start switching code over to your method.

Reply to this Comment

Ben -

Another point about your method -- it borks with the padding. If my title text wraps, then the padding on the left will not equal the padding on the right. This probably isn't a big deal for titles, as it won't be so obvious, but for paragraph content it could be a problem. I've used the same technique for callouts and blockquotes, like so:

http://rickosborne.org/school/cet4583/a1.html

That page was done for an assignment for my web development class for school, so ignore all the goofy JavaScript crap that was required for the assignments, but you can see the methodology I was talking about. The pullquote in purple uses negative margins to break out of the box. Your method would lead to strange padding.

Reply to this Comment

There are at least two really good use cases for negative margins:

* Centering an element - By setting an element with a "left: 50%" and a negative margin of half the elements width you can very easily center an element on the page. It's also a case where the negative margin makes sense.

* Columizing a list element - using a negative margin-top is one way to easily convert an ordered list into columns. It allows you to use compact semantic HTML, but still divide the list into columns.

Reply to this Comment

@Rick,

Yeah, I figured that would happen with the padding. That's why I was saying if you know the exact width, you can use explicit widths which will work nicely with the box model. However, when it comes to things like paragraphs and titles, I kind of feel that those shouldn't have explicit widths, but rather just fit with the parent.

I think your use of the negative margin is probably the *easiest* way to solve the problem without adding extra markup containers.

While I have not used your technique personally, I think it is ok. More than anything else, I want people to stop and really think about their negative margins. I am in the middle of re-coding a site right now that crazy negative margins all over the place because it was done to fix core problems with the CSS. Now, I have clean it all up :(

Carry on with your negative margin titles, blockquotes, and what have you.

Reply to this Comment

@Dan,

Yeah, that negative-left margin for the centering of things like light box is wicked cool. Again, one of the cases where negative margin does make life easier.

I am not sure I follow about the list customization.

Reply to this Comment

@Robert:

While you can use can use a negative top to specify the position, using a negative marginTop is nice because you only have to apply the negative margin to the first element in the new column. If you use negative top margin, then you have to carry the negative value to each item in the second column.

Reply to this Comment

Do you know of a better way than described in this article I just found to have a semantic, validating, minimalistic xhtml and css without using negative margins?

http://www.mindfly.com/blog/post/2009/01/Get-Refreshed-Liquid-Layouts-With-Simpler-CSS-and-Without-A-Semantic-Mess.aspx

Floating by it's nature causes semantic nightmares yet the negative margin solution does bug me a little. However this is the ONLY layout that I have found that doesn't use floats and still manages to control the column lengths without pesky height issues and has no extra divs or spans.

I'd be interested in hearing your input and if you think it's worth it or not.

Reply to this Comment

negative margins are the devil.

abs positioning != margins in any way. negative positioning in 3d programming is totally kosher and expected. the perspective is only slightly different in page layout since the origin starts at the top left rather than center.

to me, using negative margins proves you haven't constructed your document correctly [or you're forced to work with some other guy's layout].

thanks for being strong man - fight the power!

Reply to this Comment

@Dan,

I've had that Smashing mag article open in a tab for like two weeks! I haven't yet carved out time to read it, but I refuse to close it (cause I know I'll never get to it at that point).

Reply to this Comment

@Dan,

Even after reading that Negative Margins articles, I'm not fully convinced. To be honest, some of the explanations of behavior went a bit over my head. And, the fact that behavior is different for floats... I don't know.

The one thing that I have used it for is centering modal windows and that works quite nicely.

Reply to this Comment

Hi Ben. I agree, negative margins suck. This usually only means that the person writing it must have messed up the markup somewhere. Although not illegal (but just as weird sometimes), CSS like this needs to be used sparingly. I still prefer to optimize my css code whenever I can, diminishing my negative margins if there are any since it helps me sleep better at night.

Btw, I'm an avid reader of your posts. I'm actually flattered you read one of my articles.

Reply to this Comment

@John,

Yeah, right now, pretty much the only place that I use negative margins is when trying to position an absolute / fixed position modal window. Something where I can go left: 50%, margin-left: -300px. That kind of thing. Other than that, I really have not seen any need to use it.

I'm always happy to read great stuff :) Thanks for putting it out there!

Reply to this Comment

@Ben,

I agree. Margins rule compared to using top:100px or some other location to an absolutely positioned element. It's not even worth being replaced even if you added position:relative to the parent element.

Reply to this Comment

I'm really late to the party here (I blame the snow in the UK!) but I was looking up negative margins and came across this post.

I just wanted to say that I don't agree with leaving out extra markup to make logical divisions in your page and then having to fix it with negative margins. Rick's example assignment page should be divided into a header, and content section with a quote (for want of a better name) section inbetween and each will have their own appropriate styles - no need for negative margins.

I think that sometimes we can be a bit over the top trying avoid extra markup but it this case it is not extra, it makes logical layout sense and therefore makes things clearer for the next person who has to edit your code, and the different sections will even be in seperate template files for dynamically generated content.

Just my £0.02 worth.

Reply to this Comment

I have just recently started to get really focused on creating a personal web site and pretty much know lots of the basic HTML jargon and Javascript stuffs, but as far as Negative Margins and Position go I'm a tad confused.

As I understand it, Negative Margins position Divs and Blocks anywhere within the parent (even if it means that it will spill over the parent) via the Margin.

Positioning does the exact same thing..... but it seems far easier to code for 'Position' than it does for 'Negative Margins'. Am I missing something here or does the Negative Margins way of coding have some other effect? (Other than the 50% minus width of site, to center, that is an awesome trick!)

Reply to this Comment

Negative padding (or rather negative margins) are used quite heavily in the wordpress admin panel. It was the easiest way that we could have the sidebar a fixed size but have the 'content' fill the rest of the page without using loads of absolutely positioned elements and it works pretty well (well I would say that being a wordpress core developer).

Reply to this Comment

Love it. I completely agree. If a negative margin is needed then something went awry or could have been accomplished in a better way. It's a "valid" hack, that's all. I feel like a two-dollar-hooker when I ever use them. It's like having that ding on your brand new car that no one can see. BUT YOU know it's there. And the ding was intentionally put there because the door wasn't hung properly. So, to make it fit, you took a ball ping hammer to the edge of the door. :)

Reply to this Comment

Then again, Women have a size "Zero". Who am I to argue the genius that walks the halls of a fashion institute.

Reply to this Comment

Re: Website design that uses NEGATIVE MARGINS. Struggling to figure out an alternative that works...

OBJECTIVE: allow my website to look sensible on any size of screen. I don't want to use Javascript for basic website layout if I can avoid it. I want div.main to be centrally positioned and have width increase linearly with browser window width according to the formula:
300px + 33% (width of &lt;body&gt;); min-width:460px.

MY SOLUTION:

/*Minimum width of div.main is 33.4% of 1380 pixels = 460 pixels. So designed for >= 480px wide screen.*/
body {
margin-left:-690px;
margin-right:-690px;
background-color:#c1cbd4;
}
div.main{
margin-left:33.3%;
margin-right:33.3%;
background-color:white;
}

ISSUES WITH MY SOLUTION: This can lead to the scroll-bars on your browser being configured according to the outside of the margins on your &lt;body&gt; tag. Otherwise the design appears to work.

CAN ANYONE suggest an alternative that works, does not use Javascript, and uses no negative margins? Please?

Reply to this Comment

...Just to explain my previous comment... The idea is that on small screens <= 480px, div.main will have 460px width with 10px margins. On larger screens, div.main's width will asymptotically approach 33.4% of the width of the body tag.

Reply to this Comment

Hi,

Here is a practical use to using negative margins used by many...

Context : Centering an html element (potentially) larger than it's parent.

Let's say we need an html structure that accepts large varying content

<div class="outer" style="overflow:hidden">
<div class="inner" style="margin:0 -2000px;text-align:center;">
<img /> or <video style="margin:auto">
</div>
</div>

Cheers

Reply to this Comment

I'm pretty sure I have used negative margins, but haven't used them a lot. Sometimes, when you are required to do a project, and you don't know css very well, but you are required to do it and make it work for work, you have to resort to jerry-rigging your code, and I have been known to do that a time or two. I generally try to code according to set standards of the industry, but when I am in a rush for time and nothing seems to be working, and it is a project for work, sometimes I just have to try a hack and make it work.

@adg, they also have a size double zero (00). I actually have a skirt that is a size 00, but I doubt seriously I can wear it anymore. I could a couple of years ago, though. But I'm generally not a size 00, and typically I don't find women who are all that attractive (not that my opinion matters, because I am a woman, but still...)

@Ben, it's cool that you don't want negative-margin fingers touching your box models, but what about your curvy models? Can your curvy models be touched by negative-margin fingers? :-D

Reply to this Comment

We use negative margins to create tabs in the header of our pages http://www.livingincomfort.com/. The problem is that it messes with the rest of the page - specifically, the search bar in the very next element - in certain browsers it causes the search bar to be misaligned with the colored bar.

Can anyone suggest a better way to create these tabs which won't cause all these other problems?

Thanks

Reply to this Comment

Post A Comment

You — Get Out Of My Dreams, Get Into My Comments
Live in the Now
Oops!
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.