1

I understand that items within a flex container obey different rules for margin collapsing than they normally would (i.e. when not within a flex wrapper). However, the container itself's margins should still behave normally, right? In other words, why are the margins different in the two containers in this CodePen?

border collapse example

h1, h2 {
  margin: 2rem 0;
}

.inline-flexed,
.flexed {
  margin: 2rem 0;
  align-items: center;
}

.inline-flexed {
  display: inline-flex;
}

.flexed {
  display: flex;
}

.left {
  display: inline-block;
  width: 2rem;
  height: 2rem;
  background-color: blue;
}

.right {
  line-height: 1.5;
  background-color: lightgray;
}
<h1>I have margins!</h1>

<span class="inline-flexed">
    <span class="left"></span>
    <span class="right">My container is inline-flex'ed. For some reason my parent's container's margins don't collapse.</span>
</span>

<h2>I also have margins!</h2>

<span class="flexed">
    <span class="left"></span>
    <span class="right">My container is flex'ed. My parent's container's margins collapse as you'd expect.</span>
</span>

<h2>Is this a browser bug?</h2>
Engin
  • 755
  • 7
  • 20
Matt
  • 11
  • 3
  • `inline-*` element aren't a part of the margin collapsing rules: https://www.w3.org/TR/CSS2/box.html#collapsing-margins (only block level elements are) --> *Margins of inline-block boxes do not collapse (not even with their in-flow children).* – Temani Afif Apr 05 '21 at 13:40

1 Answers1

2

inline-flex generates a flex container that is inline-level element. Margin of inline-* elements does not collapse.


It is documented here.

Inline-flex

This value causes an element to generate a flex container box that is inline-level when placed in flow layout. w3

Two margins are adjoining if and only if:

  • Both belong to in-flow block-level boxes that participate in the same block formatting context.

  • no line boxes, no clearance, no padding and no border separate them (Note that certain zero-height line boxes (see 9.4.2) are ignored for this purpose.)

  • both belong to vertically-adjacent box edges. w3

Similar question

Margin collapsing in flexbox

More info

https://www.joshwcomeau.com/css/rules-of-margin-collapse/

https://www.smashingmagazine.com/2019/07/margins-in-css/

mahan
  • 12,366
  • 5
  • 48
  • 83