Stephan Bönnemann Stephan Bönnemann - 4 months ago 29
CSS Question

Flex-box ignores wrapped children's margin (margin collapse)

Given the following HTML:

<div class="outer">
<div>
<div class="inner">A</div>
</div>
</div>
<div class="outer">
<div class="inner">B</div>
</div>


and the following CSS (prefix free):

.outer {
display: box;
box-orient: vertical;

height: 100px;
width: 100px;

background: red;
margin: 10px;
}

.inner {
height: 50px;
margin-top: 10px;
background: green;
}


A and B

Here is a CodePen.

A
is wrapped in a
<div>
so it's margin gets ignored.

Q: How can I achieve
B
's behavior for
A
(margin) with the flex box model?


Note: The div wrappers can go multiple levels deep

Targeting: latest Chrome/Safari/iOS

Thank you very much for your help!

Edit: Thanks to @Jos├ęCabo I came up with this:

.outer {
display: flex;
flex-direction: column;

height: 100px;
width: 100px;

background: red;
margin: 10px;
}

.inner {
height: 50px;
margin-top: 10px;
background: green;
}


CodePen

Chrome:
Chrome

Safari:
Safari

Unfortunately it doesn't work in Safari as mentioned by @cimmanon, so I still need some help.

Answer

Finally I came up with the right solution (for my specific problem).

.outer {
  display: flex;
  flex-direction: column;

  height: 100px;
  width: 100px;

  background: red;
  margin: 10px;
}

.inner {
  height: 50px;
  margin-top: 10px;
  background: green;
  display: inline-block;
  width: 100%;
}

CodePen

I'm using display: inline-block on .inner to disable margin collapsing and then compensate for the lost width with width: 100%.

All the credit goes to cimmanon for pointing me in the right "margin collapse" direction