Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flex container overflow if previous sibling is floated

If a previous sibling is set to float with a width of 100% and the following sibling set to display: flex, the latter overflow the parent container instead of wrap to a new line.

With any other display value but flex (or grid) it wraps, as it should, so how come it won't when set to flex

.float-left {
  float: left;
  width: 100%;
}

.display-flex {
  display: flex;
  background: yellow;
}


/* Demo css */

.container {
  max-width: 80%;
  margin: auto;
  background: white;
}
<div class="container">
  <div class="float-left">I'm floating left, with a width of 100%.</div>
  <div class="display-flex">'Floating left' takes up 100% of the space, but still i don't go onto a new line?</div>
</div>
like image 637
Ubby Avatar asked Aug 29 '17 10:08

Ubby


1 Answers

The reason a block box appears to wrap when its previous sibling is a float with 100% width is because it's not actually the box that's wrapping, it's its inline content that's wrapping.

The reason this doesn't happen with a flex container is because floats cannot intrude into flex formatting contexts. In fact, the same thing happens with block formatting contexts — if you apply overflow: auto or overflow: hidden to the following sibling without display: flex the following sibling will seem to disappear altogether. (This implies that the first paragraph is true only when the block box does not establish a block formatting context.)

Since your float is 100% width, the flex container's (auto) width is reduced to 0. Its inline descendants don't wrap underneath the float, because those inline descendants are participating in an inline formatting context that's within an anonymous flex item, which itself doesn't wrap since it's the only flex item in the flex container. This flex item is overflowing the flex container; however the flex container itself doesn't overflow the containing block since its used width is 0, allowing it to sit next to the float.

The reason the flex container will wrap if it is display: inline-flex instead of display: flex is because an inline-level flex container behaves just like any other inline-level content, wrapping around a float. In this case, it's the flex container itself that wraps — its inline content is still formatted as an anonymous flex item, because flex layout is identical regardless of whether the flex container itself is inline-level or block-level.

like image 130
BoltClock Avatar answered Nov 01 '22 16:11

BoltClock