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:
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.
How to Avoid Margin Collapse. First, remember that margins should preferably be used to increase the distance between sibling elements, not to create spacing between a child and a parent. If you need to increase space within the Flow layout, reach first for padding if possible.
The first thing that stops collapsing is situations where there is something between the elements in question. For example, a box completely empty of content will not collapse it's top and bottom margin if it has a border, or padding applied. In the example below I have added 1px of padding to the box.
The top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the individual margins (or just one of them, if they are equal), a behavior known as margin collapsing. Note that the margins of floating and absolutely positioned elements never collapse.
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>
From IE8 you could do:
<div class="uncollapse-margins"> <p>Lorem ipsum dolor sit amet.</p> </div> <div class="uncollapse-margins"> <p>Lorem ipsum dolor sit amet.</p> </div>
With CSS:
.uncollapse-margins:before, .uncollapse-margins:after { content: "\00a0"; /* No-break space character */ display: block; overflow: hidden; height: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With