Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force margins to collapse on floating elements?

Tags:

css

css-float

I am trying to figure out a way to collapse margins on floated divs.

Dividing the margin side by 2 won't work… The divs' margins need to collapse b/c each div needs a different margin size (in order to look correct & be pixel-perfect against the design).

Absolute positioning won't work… The divs need to be in-flow so text won't clip against the divs.

Inline-block might not work… Some of these divs need to be aligned against the bottom of their parent, while still having text flow around them. I haven't been able to figure out how to accomplish this with inline-blocks instead of floats.

Is there anyway to accomplish collapsed margins on floats?

edit: If this reads as purposefully-vague, that's because I'm trying to save you all the massive headache of considering the whole nightmare-of-a-design that I'm trying to implement.

edit 2: After writing this, I just realized how to solve my particular problem without having to collapse margins on floats, although I would still like to know if it is even possible!

like image 324
Matthemattics Avatar asked Jun 27 '13 18:06

Matthemattics


People also ask

What causes margin collapse?

Margin collapse occurs when vertically adjacent margins of block-level elements collide to share a general margin space. The size of this shared space is dictated by the larger number margin. You can visualize this as an arm wrestling match, where the larger margin will take over and win.

In which scenario margins will collapse?

If there is no border, padding, inline content, height , or min-height to separate a block's margin-top from its margin-bottom , then its top and bottom margins collapse. Some things to note: More complex margin collapsing (of more than two margins) occurs when the above cases are combined.

Why are my margins not collapsing?

Margins of elements do not collapse when the value of the overflow property of the elements is set to anything other than visible. Its value must be visible so that margin can collapse.

Can padding collapse?

You can think of padding/border as a sort of wall; if it sits between two margins, they can't collapse, because there's a wall in the way. The width doesn't matter, either; even 1px of padding will interfere with margin collapse.


2 Answers

Basically what you have to do is add a bit more markup.

You can enable margin-collapse on floated elements by wrapping the floated element in a div with the desired margin declared.

I explain in further detail and give an example here http://codepen.io/nicksaemenes/pen/moutp

like image 76
Nick Saemenes Avatar answered Oct 03 '22 12:10

Nick Saemenes


Andy Budd said a long time ago:

If you float a box, its margins no longer collapse.

like image 30
Michael McGinnis Avatar answered Oct 03 '22 14:10

Michael McGinnis