Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I uncollapse a margin? [duplicate]

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.

like image 812
Alex J Avatar asked Dec 01 '09 20:12

Alex J


People also ask

How do you overcome margin collapse?

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.

Why are margins not collapsing?

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.

What is margin collapsing?

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.


2 Answers

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> 
like image 53
Zenon Avatar answered Oct 09 '22 12:10

Zenon


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; } 
like image 25
andraaspar Avatar answered Oct 09 '22 11:10

andraaspar