1

I have a div with floated children.

I know I can stretch the height in the following 2 ways:

.container {
  border: 2px solid #ccc;
  margin-bottom: 250px;
}

.container-2::after {
  content: '';
  display: block;
  height: 0;
  font-size: 0;
  clear: both;
}

.container-3 {
  overflow: hidden;
}

.item {
  float: left;
  width: 200px;
  height: 50px;
  background: red;
  margin: 10px;
}
<div class="container container-1">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

<div class="container container-2">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

<div class="container container-3">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

But I think they have the different principles: the clear:both ::after element stays away from the float brothers, and force the parent div to stretch the height; the overflow:hidden style makes the div have the BFC, and according to standard, BFC will stretch its height to include its float children.

The advantages and disadvantages are not important,but the how they works.

Am I right, they are different but have the same result?

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
yanni4night
  • 137
  • 7
  • Possible duplicate of [clear:both or overflow:auto, which is better?](http://stackoverflow.com/questions/15725667/clearboth-or-overflowauto-which-is-better) – Aziz Apr 10 '16 at 02:20

1 Answers1

3

Do clear:both and overflow:hidden work the same way to make a container wrap floated children?

No. They perform different functions.

clear:both

The clear property controls whether an element can be next to or below floated elements that come before it. It controls whether an element can clear the floated elements.

clear:both, when applied to a non-floating, block-level element:

Requires that the top border edge of the box be below the bottom outer edge of any right-floating and left-floating boxes that resulted from elements earlier in the source document.

source: https://www.w3.org/TR/CSS2/visuren.html#propdef-clear

So the clear property more likely applies to a sibling of floated elements. It has nothing to do with stretching the height of div which has float children (as stated in your question).

overflow:hidden (or overflow:auto)

The overflow property, when used with a value other than visible, creates a new block formatting context. This causes the element containing floats to expand in order to contain its floated children.

In summary, one property clears an element past floated elements. The other stretches the container to wrap floated elements. The output may appear the same for both. But each property is fundamentally different.

Further reading:

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701