yanni4night yanni4night - 2 years ago 65
HTML Question

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

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 class="container container-2">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>

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

But I think they have the different principles: the
::after element stays away from the float brothers, and force the parent div to stretch the height; the
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?

Answer Source

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

No. They perform different functions.


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:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download