How do I uncollapse a margin?

Alex J picture Alex J · Dec 1, 2009 · Viewed 16.3k times · Source

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.

Answer

Zenon picture Zenon · Dec 1, 2009

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>