views:

160

answers:

2

Collapsing margins in CSS: http://www.w3.org/TR/CSS21/box.html#collapsing-margins

I understand the purpose of the feature, but I'm trying to do layout, and I can't figure out how to turn it off.

The way usually explained in CSS tutorials is to either:

  1. Add a border
  2. Add a padding

All of these have side effects that become obvious when you're dealing with pixel-perfect layouts with background images and fixed paddings.

Is there any way to simply disable the collapsing without having to shove extra pixels into the layout? It doesn't make any sense for me to have to visually affect the document to change behavior like this.

+2  A: 

well you need something in between to "break" the collapsing.

my first thought was to use a div with display:none set in between, but that doesn't seem to work.

so I tried:

<div style="overflow: hidden; height: 0px; width: 0px;">.</div>

which seems to do the job nicely (at least in firefox, don't have internet explorer installed here to test it...)

<html>
    <body>
        <div style="margin: 100px;">.</div>
        <div style="overflow: hidden; height: 0px; width: 0px;">.</div>
        <div style="margin: 100px;">.</div>
    </body>
</html>
Zenon
Works for me in Firefox, Chrome, Opera and IE6 on Linux. Good job, I was about to post that it was impossible...
DisgruntledGoat
Seems to work in IE6 as well. It's astounding that you need extra markup to acomplish this though.
Ilia Jerebtsov
Actually, close, but not quite there. The margins are still collapsing, they're just not collapsing against eachother. Consider: <div style="background-color: red;"> <div style="margin: 100px;">.</div> </div> <div style="overflow: hidden; height: 0px; width: 0px;">.</div> <div style="background-color: blue"> <div style="margin: 100px;">.</div> </div>
Ilia Jerebtsov
well, id you put the overflow:hidden div inside the background divs, it still works (though the markup is getting uglier and uglier this way...).like <background div><overflow div/><margin div/><overflow div/></div>there has to be a more elegant solution to this. Though, knowing how webdesign is, there probably isnt :)
Zenon
+2  A: 

Eric Meyer refers to your exact point in his article Uncollapsing margins.

See the text of the article after Figure 6 for his approach. He mentions that 1px padding/border is typically the way to go, but offers a pretty simple solution for instances where there's no flexibility in adding that additional pixel.

It involves manually overriding margins on each element though, so I'm not sure if it will work for your particular case.

Mark Hurd