August 1st, 2007 - by Paul OB

I’ve been thinking negatively once again and instead of keeping my thoughts to myself I thought I’d share them with you. In this article we look at how negative margins work and how to apply them in everyday usage.

A number of people suffer under the misconception that negative margins are in some way a hack; they are not. In fact negative margins are valid CSS and extremely useful in certain situations. They only become a hack if you are using them to fix an error that you have made elsewhere. In normal usage negative margins work quite well and are supported across modern browsers. However, there are issues if you use negative margins on the opposite side of a float (e.g. floating left and then using a negative margin on the right) although most modern browsers now behave the same way when this happens. In some of the examples below you will see what I mean. Let’s dive in!

Negative Margins on Static Elements

First we’ll look at how non-positioned (static) elements behave when negative margins are used. In order to do this we need a point of reference so we can see the effect. Therefore we will construct a number of paragraphs that all have a 20px top and bottom margin. You may recall from my collapsing margin article that adjacent margins of static elements will collapse into one margin. So each paragraph will be 20px apart.

e.g.

  1. p{
  2. margin:20px 0;
  3. height:40px;
  4. background:#ffffcc;
  5. border:1px solid #000;
  6. }
  1. <p>This is the paragraph 1</p>
  2. <p>This is the paragraph 2</p>
  3. <p>This is the paragraph 3</p>
  4. <p>This is the paragraph 4</p>
  5. <p>This is the paragraph 5</p>

If you run the above code you will see a display like Figure 1.
Figure 1:
ex1.gif

Now let’s suppose you wanted the second paragraph to be only 5px away from the one above it, how would you achieve this? First you would need to add a class to the first and second paragraphs. Secondly, you give paragraph 1 a 5px bottom margin and paragraph 2 a 5px top margin (look for the margins to collapse into one).

  1. p.top{margin:20px 0 5px 0}
  2. p.bottom {margin:5px 0 20px 0:}
  1. <p class="top" >This is the paragraph 1</p>
  2. <p class="bottom" >This is the paragraph 2</p>
  3. <p>This is the paragraph 3</p>
  4. <p>This is the paragraph 4</p>
  5. <p>This is the paragraph 5</p>

As expected this produces exactly what we want in Figure 2.
Figure 2:

ex2.gif

The gap is now 5px between paragraphs 1 and 2 and the rest have the original 20px margins.

Could we have done this with less code?

As a matter of fact we can reduce the code considerably if we use a negative margin on the second paragraph. By applying a negative margin of -15px on the second paragraph we get exactly the same effect.

  1. p.bottom {margin:-15px 0 20px 0;}
  1. <p>This is the paragraph 1</p>
  2. <p class="bottom" >This is the paragraph 2</p>
  3. <p>This is the paragraph 3</p>
  4. <p>This is the paragraph 4</p>
  5. <p>This is the paragraph 5</p>

The negative 15px margin pulls the second paragraph upwards by 15px without moving paragraph 1 and leaves us with a 5px gap exactly as shown in figure 2 above. This saves us 1 line of CSS and also saves us from adding a class to both the first and second paragraphs. Therefore, for cleaner code the negative margin approach wins hands down!

It should be noted that if you wanted to pull the paragraph up further so that it overlapped the one above then you would need to add position:relative to the mix so that you can control the stacking context with z-indexes. Although by default the bottom paragraph will usually overlap the top but this is not always the case and it is left up to the User Agent to decide where nothing has been set explicitly. (It should also be noted that IE will usually prefer position relative to be added if you pull an element out of its parent container when using negative margins, otherwise on occasions it hides the part that is sticking out.)

So we have established that on static elements positive margins collapse to the greater margin set but when a negative margin is thrown into the mix then the negative margin is subtracted from the positive margin to reveal the final margin. (e.g. In the example above 20-15 = 5). Therefore it’s easy to deduce that if the negative margin is greater than the positive margin then some sort of overlap will take place. This is worth a quick example — using the code above but amended as follows.

  1. p.bottom {margin:-35px 0 20px 0;}

Our calculations will say that -35px – 20px = -15px, which should give us a 15px overlap with the lower paragraph over the top.

As you can see from figure 3 that is exactly what happens.
Figure 3:

ex3.gif

(I shifted the second paragraph a little to the right so you could see that is does overlap the one below.)

The above example shows that negative margins will cause static elements to overlap, unlike positive margins which push static elements away. So using negative margins in the above manner is in fact very safe and shouldn’t cause any problems at all for the modern browsers.

Next let’s look at another useful method — how to make the box on the inside wider than its parent.

The space on the inside is bigger than the space on the outside.

This has nothing to do with the space time continuum and is simply a matter of applying negative margins to both sides of a container. We will construct a fixed width container and then drag the inner container outside of the parent using negative margins to pull both left and right sides outside of the parent. Here is the code to do this:

  1. .outer{
  2. margin:50px;
  3. padding:20px 0;
  4. width:200px;
  5. background:#ffffcc;
  6. border:1px solid #000;
  7. }
  8. .outer p {
  9. margin:0 -20px;
  10. background:red;
  11. color:yellow;
  12. border:1px solid #000;
  13. padding:5px;
  14. }
  1. <div class="outer">
  2. <p>This is the paragraph that we want to stretch outside the parent for a neat effect</p>
  3. </div>

If you run this code in Firefox 2.0 you will get the desired result as shown in figure 4.
Figure 4:

ex4.gif

However, if we look at IE6 and IE7 we get rather different results as shown in figure 5.

Figure 5:

ex5.gif

Hmmm… that looks strange – what happened here?

In IE6 the negative margins are completely missing and in IE7 the right negative margin portion is missing.

IE7 is quite easy to fix — we just need to ensure that “haslayout” is true for the inner element. This can easily be done by applying min-height:0 which is one of the properties that will cause “haslayout” to be true in IE7. The min-height:0 is 100% safe and doesn’t need to be hidden from any browsers at all. As can be seen in figure 6 this completely rectifies the issue with IE7.

Figure 6:
ex6.gif

Since IE6 doesn’t understand min-height it won’t cause “haslayout” to be true and therefore nothing changes; both sides of the inner box are still missing. The usual fix to apply layout to IE6 is to use the height:1% hack and if we try that we get the result as shown in figure 7.

  1. * html .outer p{height:1%;}

Figure 7:
ex7.gif

As you can see, this doesn’t work very well; we get the rather strange effect seen above. If you remember earlier I mentioned that position:relative should be used to rectify stacking problems. So let’s see what happens if we add position:relative.

  1. * html .outer p{height:1%;position:relative}

Figure 8:
ex8.gif

That’s a little better but the element is just shifted to the left and does not overhang the right side as it should. You might start thinking that it can’t be made to work in IE6, but the solution is very close. If instead of using the height:1% hack we use the height:1px hack suddenly everything falls into place exactly as we want! This also fixes the layout for IE5, 5.5 and 6!

  1. * html .outer p{height:1px;position:relative}

Figure 9:
ex9.gif

Why height:1px works in this case and height:1% doesn’t work is a bit of a mystery as they both cause “haslayout” to be in place. It was thought that perhaps the 1% height defaulted to height:auto because the parent has no height. However, this doesn’t seem to be the answer because the effect is the same even if you give the parent a specific height so that the percentage height can work correctly as it has something to base its height on. It would be nice to know exactly why there is a difference here but for the time being we’ll just have to be happy to know that height:1px works for us.

Here is the full code to satisfy IE5 – 7:

  1. .outer{
  2. margin:50px;
  3. padding:20px 0;
  4. width:200px;
  5. background:#ffffcc;
  6. border:1px solid #000;
  7. }
  8. .outer p {
  9. margin:0 -20px;
  10. background:red;
  11. color:yellow;
  12. border:1px solid #000;
  13. padding:5px;
  14. min-height:0;
  15. }
  16. /* mac hide \*/
  17. * html .outer p{height:1px;position:relative;}
  18. /* end hide */

Note that the star selector hack is used here to supply the hack to only IE versions 6 and under so that other browsers do not see the height; otherwise they will limit the element to 1px height. The hack should also be hidden from IE5 Mac as it treats height correctly; so it doesn’t need the hack anyway. The strange comments are the Mac hiding hack and filter out IE5 mac from reading the styles between the comments.

In the next section we will look at how using negative margins on floats display different characteristics from those shown above.

Negative Margins and Floats

In the previous section we saw that adding negative margins to a static container pulls the container in the direction specified (e.g. margin-top:-15px pulls the container 15px towards the top). We also learned that adding negative margins to opposing sides of the element pulls the element in both those directions thus increasing the width of the element.

Now we’ll look at Floats, which as we’ll see are a different beast altogether. Floats posses some behaviors to watch out for and some to utilize.

If you float an element left you will find that adding a left negative margin will pull the element in that direction much the same as explained already for static containers. However, if you try to use a negative margin on the right side of a left floated element (or vice versa for a right floated element with a left negative margin) you will find that things aren’t all that they seem.

Using the code below we apply a negative right margin to a left floated element.

  1. .float{
  2. float:left;
  3. padding:10px;
  4. width:100px;
  5. background:#ffffcc;
  6. border:1px solid #000;
  7. height:100px;
  8. margin-left:20px;
  9. }
  10. .one {margin-right:-50px ;}
  11. .two{
  12. background:red;
  13. color:yellow;
  14. height:90px;
  15. }
  1. <div class="float one">
  2. <p>Float 1</p>
  3. </div>
  4. <div class="float two">
  5. <p>Float 2</p>
  6. </div>

This does not move the float towards the right as happens with static containers, but instead does almost the opposite — the right margin of the float appears to be moved 50px inside itself!

If you look at figure 10 below you can see how the second floated element is assuming that the first float’s margin is 50px away from where it was originally and the second float overlaps the first.

Figure 10:

ex10.gif

Looking at the image above you can see that float1 doesn’t seem to have changed in any way — it’s in the same position with the same width. The only implication of the negative margin is that other elements now treat float1 as though it was 50px smaller in width than it actually is. What’s interesting is that as far as any content inside float1 is concerned nothing has changed and the content will still use the full width available in float1. This will of course result in content being hidden if other elements overlap!

Yes – but what use is this?

So we have established that the right negative margin allows elements to approach from that side, but is that any real use to us?

As it happens, it can be used to solve a common problem where it is required for 2 floats to be side-by-side and to stretch to 100% width but where one float has a fixed pixel width. In this scenario you can easily set one float to 200px width but you can’t set the other float to 100% – 200px width. Usually this is resolved by floating the 200px width element and then using a static container with a margin big enough to avoid the float. This method works ok but it suffers badly from the three pixel jog and associated bugs in IE6 and under. It also suffers from the fact that the floated element must be first in the source order in order to work.

By using our knowledge of the negative margin behavior we can use this to our advantage to enable 2 floats to stretch to 100% width exactly. We do this by first setting one float to 100% width and give it a 200px negative right margin. We then simply float our second element with a 200px width.

  1. .float{
  2. float:left;
  3. background:#ffffcc;
  4. height:100px;
  5. margin-right:-200px
  6. }
  7. .one {width:100%}
  8. .two{
  9. background:red;
  10. color:yellow;
  11. width:200px;
  12. height:90px;
  13. margin:0;
  14. }
  1. <div class="float one">
  2. <p>Float 1</p>
  3. </div>
  4. <div class="float two">
  5. <p>Float 2</p>
  6. </div>

This gives the result as seen in Figure11.

Figure 11:
ex11.gif

The drawback here is that any content in float one will be hidden underneath float2 as shown in figure 12.

Figure 12:
ex12.gif

The solution to this is pretty simple — we just need to ensure that any content we place in float one has a margin-right that will keep it clear of the right float. This can be done by either nesting a div inside and applying a margin to the div so that all content in the div is kept clear or by applying a margin to all the individual elements inside.

e.g.

  1. .one p{margin-right:210px}

Figure 13:
ex13.gif

This results in 2 floated columns that stretch to 100% width, without suffering from the three pixel jog, and are not source order dependent.

It does look a little messy — if we want to tidy it up we can remove the colours from the parent floats which were just for demonstration purposes and apply some styling to an inner container instead.

  1. .float{
  2. float:left;
  3. margin-right:-200px
  4. }
  5. .one {width:100%}
  6. .two{
  7. width:200px;
  8. height:90px;
  9. margin:0;
  10. }
  11. .one p{margin-right:210px}
  12. p{
  13. background:red;
  14. color:yellow;
  15. border:1px solid #000;
  16. }

(The HTML is exactly as already shown above.)

And here is the result as shown in figure 14.

Figure 14:
ex14.gif

We now have our 2 columns working quite nicely!

When 100% – 100% = 0

I should point out that if you make the right negative margin equal to the elements total width then effectively the element becomes 0px wide. This is because margins, padding, borders, and width add up to the total width and therefore if the negative margin is equal to the rest of the dimensions then the elements width effectively becomes 0px. This doesn’t really affect anything in modern browsers as they will still work as per the examples above. However, in browsers previous to Mozilla 1.6 and equivalent they will almost treat the element as though it were not there much in the same way that an absolute element behaves. This makes it impossible to clear the float and it will always overlap content underneath. This does not happen in IE and Firefox 2.0. If you make sure that your negative margin is smaller than the total width of the element concerned then this problem is avoided (or if you don’t care about older browsers then don’t worry).

In this article we have covered the different ways that negative margins can be used and how the behavior differs between floated and static elements. We have also observed and squashed some bugs in IE and in the final example demonstrated how to effect 2 floated columns that stretch 100% wide where one column is a fixed width.

The examples above will work on most modern browsers, but have been specifically optimized for IE5 – 7 and Firefox 2.0 only and you should therefore check in the browsers you want to support when using these advanced methods.

47 Responses to “The Positive Side of Negative Margins”

[…] The Positive Side of Negative Margins 这篇文章中研究margin的一些情况,其中利用负值实现两个矩形重叠一起的效果非常好,只需照顾IE7与IE6,触发”haslayout”即可。 […]

2 HTML Editor Reviews » links for 2007-08-02

[…] The Positive Side of Negative Margins In this article we look at how negative margins work and how to apply them in everyday usage. (tags: css webdesign) 08-01-2007 | 11:29 pm […]

3 John

One thing to keep in mind when using negative margins which I have learnt just recently is that they won’t work at all in Dreamweaver in design view. Why should this be important? Just use code view, right? Well, sometimes you might work for a client that uses DW & Contribute to enable their clients to update their own pages. If this is the case, you’re probably better off avoiding content-first models altogether.

4 Darren

@ John
I too found this out. Luckily for me I can manage everything within code view and in fact have recently un-installed Dreamweaver but for those who haven’t are rather unlucky and the only other options are learn html correctly or get a bespoke system made to enable you to modify your content without touching the design.

I agree. Negative margins can be great when used correctly but in many places as you have said they are simply used to cover up previous problems.

5 Lim Chee Aun

Wow, this is nice. It’s been a long time I haven’t read a solid article on CSS. By the way, is that a software you use to measure the lengths?

6 gunnard

I would turn down a client before I lowered my web development standards so that they could use dreamweaver’s design view.

7 Paul OB

Thanks for the comments.

I don’t use DW in design view at all because it doesn’t handle css very well at all and I’m not surprised that contribute is just as bad.

This doesn’t mean the techniques in the article are any less worthy but only that some editors aren’t man enough for the job :)

@Lim Chee aun -the calipers I use to measure things on screen can be download for a trial from here: http://www.iconico.com

8 Christian Watson

Nice article – a great read. One minor point: is anyone still supporting IE5/Mac? Unless you’re getting millions of visitors per month I’d recommend dropping support for that browser. No one uses it.

9 John

I would turn down a client before I lowered my web development standards so that they could use dreamweaver’s design view.

That may be OK for you but in my case I was working for a client who I’d worked for before who I’d had no problem with and the site in question was for a very large, long-standing client of theirs, so in that situation it wasn’t practical for them to turn around and say: “sorry, we can’t work with you anymore”.

10 Paul OB

Hi Christian,

Yes you are correct that Ie5mac isn’t worth supporting unless you have to. I just use the mac hiding hack because my fingers always type it automatically (old habits die hard) even though i don’t have to.:)

11 pixelcup » links for 2007-08-04

[…] The Positive Side of Negative Margins “A number of people suffer under the misconception that negative margins are in some way a hack; they are not. In fact negative margins are valid CSS and extremely useful in certain situations. They only become a hack if you are using them to fix an error (tags: css design development) […]

12 NeoSwf

Paul, thank you a lot for this article!
i took your technique one step further, and made a four columns layout, with 2 centered 50% columns, and 2 sides fixed ones.

http://www.webcssdesign.34sp.com/me/negativeMarginsAcordion.htm

Great work and technique. helped me alot advancing in my field.

thank you.
Sol.

13 Paul OB

Glad you found it useful :)

[…] O’Brien shows us the positive side of negative margins on static and float […]

15 Best of July 2007 | Best of the Month

[…] The Positive Side of Negative Margins A number of people suffer under the misconception that negative margins are in some way a hack; they are not. In fact negative margins are valid CSS and extremely useful in certain situations. They only become a hack if you are using them to fix an error that you have made elsewhere. In normal usage negative margins work quite well and are supported across modern browsers. However, there are issues if you use negative margins on the opposite side of a float (e.g. floating left and then using a negative margin on the right) although most modern browsers now behave the same way when this happens. […]

16 Give Me Some Zzzzz’s

[…] Most of the time when laying elements on a page you don’t really need to consider their stacking order because the elements don’t actually overlap in the normal flow of the document. It’s only when you start positioning elements so that overlapping occurs that you need to consider which element should be on top and which element should be underneath. Elements can be positioned using absolute, relative or fixed positioning or even shifted on top of each other using negative margins. […]

[…] The Positive Side of Negative Margins A clear and concise run-down of how negative margins work in CSS. (tags: css) […]

18 Balendu Sharma Dadhich

I have seen many CSS based sites to have a lot of javascript and entangled CSSes. In fact some of the CSS based web pages I have seen are a lot weighty (in the range of 200 KB and more). On the other hand, the same pages could be made much lighter by using the table layouts (if the code is trimmed properly). Doesn’t such layouts defeat the purpose? I say this even though I am fully convinced of the good side of CSS. May be the problem is with the proper application of CSS?

19 Paul OB

@Balendu Sharmu Dadhich – I’m sorry but your reply has nothing to do with the article as this is not a debate about tables versus CSS.

This is a CSS column discussing aspects of CSS so please keep your comments relative to the article and on topic.

Thank you.

20 lost node » Blog Archive » Best of July 2007

[…] The Positive Side of Negative Margins A number of people suffer under the misconception that negative margins are in some way a hack; they are not. In fact negative margins are valid CSS and extremely useful in certain situations. They only become a hack if you are using them to fix an error that you have made elsewhere. In normal usage negative margins work quite well and are supported across modern browsers. However, there are issues if you use negative margins on the opposite side of a float (e.g. floating left and then using a negative margin on the right) although most modern browsers now behave the same way when this happens. […]

22 Sherwin Techico

Sweet. I’ve been thinking about why I use clearfix (OTL) technique in the past year or so and just couldn’t get a solid reason out of my head why I have used it more vs. negative margins w/ floats (i.e. for 2/3-column layouts, etc.) these past projects. Meanwhile, I wonder what most people use when they find themselves in a similar situation, and why? Any insight regarding this Paul, or am I missing something very specific here? TIA

23 Paul OB

Hi Sherwin,

I’m not sure I’m getting the gist of your message :)

You only need to use the clearfix routines when you want to clear floats and make content start underneath. There are a number of methods including the PIE (tony Aslett) method, the float in a float method, a solid clearing div method, and the overflow method (invented by me :)).

All have their advantages and drawbacks depending on the situation on hand. It would too much for me to detail all the benefits and drawbacks here (perhaps there’s another article here) but the method I use in most cases is the one documented at the PIE (position is everything)website because it involves no extra html markup.

24 Patrick

Fantastically clear discussion of negative margins. Very nice. Wouldn’t it be better, though, to stop using the * html hack completely and revert to conditional comments? Using that damned hack caused me so much work when IE7 came along. Who’s to say that it won’t cause just as much with the next version of IE?

25 Paul OB

Hi Patrick,

Many thanks for your comments :)

Regarding the * html hack then conditional comments are a viable alternative but the * html hack is 100% safe to target ie6 and under.

IE7 doesn’t parse the star selector hack(and in most cases doesn’t need the hacks used) so it is a 100% safe way to supply code to ie6 and under.

On the contrary if you had used previously used conditional comments using just “if IE” then you would be in a far worse state than you found yourself already because all your hacks would have applied to IE7 and in most cases it needs none of them.

If you had used conditional comments excluding ie7 then that would leave you in the exact same position as if you had just used * html anyway. There would be no difference at all between the two methods

Therefore your previous use of * html could only have had benefits over the conditional comment method or at the worst it would have been exactly the same.

A lot of people are confused by this but IE actually did quite a clever job when introducing ie7 and I found that 99% of my layouts needed no changing to accommodate it. IE7 does have “haslayout” issues but there would have been no way of predicting this or working out how to cater for it until the browser was live and testing could begin. It turns out that the easiest fix for “haslayout” in IE7 is to specify min-height:0 and no hack is needed. There was of course no way of knowing this beforehand as min-height wasn’t even on the original ie7 agenda.

When using hacks you should only target dead browsers and that’s exactly what the * html hack does now. Of course we were lucky that the IE team stopped it working in IE7 but at the same time fixed most of the issues that the hack was fixing.

I am seeing a lot of people these days go overboard on the conditional comments and where before they would think twice about using a hack, I see full stylesheets for each version of IE which makes debugging a nightmare.

If you use conditional comments then only add the specific code needed to these stylesheets but also have a strategy in your main stylesheet that identifies where the main code may differ. I often work on large sites with 20 or 30 css files and its a real pain to have to check the main file and then the various ie files just to debug a problem. In most cases a simple * html fix in the main stylesheet would make it 100% easier.

Whatever method you use you must manage it and have a strategy that works.

Regarding your last comment you can be 99.99999999999% sure that * html will not be recognized in any future versions of IE. That’s not to say that future versions of any browser won’t have bugs but they won’t suddenly revert to a previously well known incorrect way of parsing styles.

26 Patrick

Fair enough, Paul! You make a convincing argument. I suspect I wasn’t using the * html hack very well and that my basic css wasn’t as good as it should have been.

27 award tour » positive side of negative margins

[…] The Positive Side of Negative Margins. great article on css layout with negative margins. […]

28 John Snyders

This is the best explanation of negative margins I have seen.

My question is about using negative margins and floats to create a two column layout.

I understand the motivation for putting the content first and sidebar second (in document order) but if the sidebar *did* come first what would you expect the effect to be?

I had a page where the sidebar did come first and it was working fine on IE6/7, Opera 9.25 and Firefox 2. It doesn’t work with Firefox 3rc1 or Safari (3.0.4 on Windows)

The problem is that mouse clicks in the sidebar are ignored. You can’t click inputs or links or select text. You do have keyboard access to them. Also if the float with negative margin has a background color it covers the sidebar.

Is there some CSS rule that says the float with negative margin must come first?

I asked the question on the Firefox discussion group also. There is an example that shows the issue there.

http://groups.google.com/group/mozilla.dev.apps.firefox/browse_thread/thread/a42bcf6bf689bcf2?hl=en#

[…] The Positive Side of Negative Margins A clear and concise run-down of how negative margins work in CSS. (tags: css) […]

30 rajeev mehta

hi paul thanks for the great article but when I try to give a border to the two boxes the second box shifts down and it doesn’t overlap the first one even though I have kept the margin-right for the first box -200px.Can you please clear my doubt regarding this.. Thank you

[…] The Positive Side of Negative Margins A clear and concise run-down of how negative margins work in CSS. (tags: css) […]

32 Zoffix Znet

All I want to add is that if your container does not have fixed height, you can give both IE6 and IE7 “layout” using foo { height: 1% } and not have to hide it from sane browsers because it would compute to `auto` anyway.

I’ve documented the negative margin on http://haslayout.net/css/view?tut=Negative-Margin-Bug if anyone cares.

Cheers!

33 Paul OB

Hi Zoffix,

Thanks for your comments.

You obvioulsy skipped over the part where I mention that the height:1% hack does not actually work in this case and it has to be height:1px which “must” only be given to IE6 otherwise everyone else only gets 1px height.

It is also very risky to recommend that authors use height:1% for all because it will cause problems when the parent element has a set height and then the 1% will resolve to 1% and you will get very little content showing.

Although height:1% can be used safely where the parents are height:auto I would advise against it because it’s an accident waiting to happen.

Separating the hack into a specific ie6 only rule means that it is safe forever even when you go back at a later date and add heights to your parents for whatever reason.

Consistency is the key here :)

34 Zoffix Znet

Hey, yeah, I skipped over that bit. By no way was I recommending anything, as you can see in my bug tutorial I recommend using conditional comments.

Anyway, what I notice that if `height` is set in percentages (irrelevant of whether the parent has set height or not) then the right negative margin refuses to “work” (i.e. it does not move to the outside of the parent) it does not get fixed by giving the element “layout” using any other method and increasing the value of the margin does not make it go out either. Was just wondering if you know a fix for this problem already.

Cheers

35 Zoffix Znet

Another thing I just noticed while trying to fix that IE6 bug is that setting `right` property to any value (even auto) will cause the same problem – negative margin does not escape the container.

I’ve set up a demo for both of those setups that break in IE6 here: http://haslayout.net/demos/ie6-unfixable-right-negative-margin-bug-demo.html

If anyone ever finds a solution, let me know.

Cheers

36 Zoffix Znet

Sorry for the comment flood (can you tell I have ADHD, eh?) but just wanted to mention that this same problem exists in IE7 as well.

Cheers

37 Paul OB

Hi Zoffix,

I think I already covered these issues in the article and you need height:1px (not 1%) for IE6 and then use min-height:0 for IE7.

The right:auto on position:relative means nothing so should be removed because it is confusing IE.

The css should be like this:

.example1 {
background: #F5F5F5;
padding: 10px 0;
width: 500px;
height: 100px;
margin: 10px auto;
border: 1px solid #000;
}
.example2 {
background: #A5A5A5;
margin-right: -500px;
position: relative;
border: 1px solid #000;
}
.example2 {
display: block;
}
.example3 {
height: auto;
}
* html .example2,* html .example3{height:1px}
.example2,.example3 {min-height:0}

That seems to make both negative margins work as expected.

Hope that helps

38 Zoffix Znet

Sorry, but that didn’t help. The `height` in percentages set on the first example is not for giving layout; I already have `display` property there giving it. Let’s pretend it’s by design; one wants to have a percentage height of the parent. It’s broken there.

I know that `right: auto` does nothing, that was to show in the demo that setting it to any value causes the bug in IE6 and 7. Let’s pretend it’s `right: 20px`.

Cheers

39 Paul OB

Ah sorry – I misunderstood – I’ll take another look :)

40 Paul OB

Hi Zoffix,

Example 2 can only seemed to be fixed by changing the height:100% to height 100px which will fix the problem but makes using percentage heights impossible.

Although I can’t really think of an example where the parents height wouldn’t be known in this scenario and that you could use pixel heights anyway. If the parent has a height then you can always use a pixel height and solve the problem. Therefore the example seems to be unsolvable but a little contrived as there would be a solution using pixel heights in nearly all cases I can think of.

However it is still a nasty bug :)

Example 3 can be fixed quite easily with extra html and you just need to use an inner element to hold the relative offset.

Nest a span inside example 3 and use this.
e.g.

.example3 span{
position:relative;
zoom:1.0;
right:20px;
border: 1px solid #000;
background: #A5A5A5;
width:100%
}

Of course that would need to be only given to IE6/7 and hidden from others (and the original styles on .example 2 amended to remove the background and borders etc).

Interesting demos though :)

[…] Search This, The Positive Side of Negative Margins […]

42 Sylwester w Górach

I never thout about using negative margins but it gives some ideas about what new can i do on my website, The more i read this articles the more ideas i have.

43 Jesse Taylor

I found this very useful, not only for learning about negative margin techniques, but for gaining a better grasp of the box model and layouts in general. Your images are excellent by the way — I love the calipers :)

Thanks for putting this all together!

44 Kamrul Hasan

Exactly what I needed. I was trying to modify wordpress twenty ten theme where they have applied this float and negative margin tricks. Now I know and I will be a better coder next time. Thanks a lot!

45 Ignacio Cortorreal

Very funny and interesting your use of the Vernier Caliper in your examples. LOL. I found this page while looking for information about using negative margins in email templates.

46 Paul OB

@Ignacio: I’m still using them 5 years later and they are on my screen at the moment(I upgraded to the paid version though):)

[…] Search This, The Positive Side of Negative Margins […]

mulberry sale spyder womens jacket cheap new balance 574 mulberry outlet cheap new balance 574 arcteryx outlet mulberry sale spyder womens jacket mulberry sale spyder womens jacket mulberry outlet mulberry outlet new balance 574

Popular Articles

Top 10 Commentators


Subscribe to this feed! Subscribe by Email!

Random Bits Podcast

You need to download the Flash player from Adobe

Blogs Worth Reading