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:
- Add a border
- 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.
From IE8 you could do:
With CSS:
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:
which seems to do the job nicely (at least in firefox, don't have internet explorer installed here to test it...)
One neat trick to disable margin collapsing that has no visual impact, as far as I know, is setting the padding of the parent to
0.05px
:The padding is no longer 0 so collapsing won't occur anymore but at the same time the padding is small enough that visually it will round down to 0.
If some other padding is desired, then apply padding only to the "direction" in which margin collapsing is not desired, for example
padding-top: 0.05px;
.Working example:
Edit: changed the value from
0.1
to0.05
. From this small test, it seems that Firefox takes the0.1px
padding into consideration. Though,0.05px
seemes to do the trick.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.
Use Flex or Grid layout.
In flex and grid containers, there's no such thing as margin collapsing.
More details in the specs: