Andrea
Andrea

Reputation: 16560

Why do floating parent with floating children does not collapse?

Why if a div element is floating, and has all its children floating, it does not collapse (as a "normal" div would do)?

Here there is an example https://codepen.io/anon/pen/MOPMPz

HTML

<div class="float">
  <div class="elem">Elem 1</div>
  <div class="elem">Elem 2</div>
  <div class="elem">Elem 3</div>
</div>

<div class="clear"></div>
<br>

<div class="no-float">
  <div class="elem">Elem 1</div>
  <div class="elem">Elem 2</div>
  <div class="elem">Elem 3</div>
</div>

CSS

.clear {
  clear: both;
}

.float {
  background-color: salmon;
  border: 2px solid purple;
  float: left;
}

.no-float {
  background-color: red;
  border: 2px solid purple;
}

.elem {
  border: 1px dashed green;
  float: left;
}

Result

enter image description here

My expected result was to see both divs (.float and .no-float) collapsing.

Where can I find some resource explaining this?

Upvotes: 2

Views: 85

Answers (1)

DSCH
DSCH

Reputation: 2366

According to Mozilla docs:

...when an element is floated, it is taken out of the normal flow of the document (though still remaining part of it). It is shifted to the left, or right, until it touches the edge of its containing box, or another floated element.

Because it is taken out of the normal flow then the "no-float" div doesn't have any content, so it's height is 0 pixels. When you make the wrapping div float, it is then in this "sub-flow" of the document and actually contains the three floating elements nested inside of it. If your layout requires you wrapping div won't be floating you can add overflow: auto; to the style of .no-float and it will "re-gain" it's height and won't behave as a float element it self.

Upvotes: 2

Related Questions