1

Is there something technically incorrect about floating and clearing in a single DIV? For example float:left begins a box formatting context and clear:both ends a box formatting context. Placing both in a single DIV appears to create a self contained BFC not unlike overflow:hidden.

Here is a simple example:

.wrapper {
    width: 50%;
    float: left;
    clear: both;
}

I tested this in every modern browser except Safari because I don't have an iPhone handy. I also tested it in IE8 through 11. In all cases it worked perfect. In addition it validated properly on CSS Lint. But I wonder if I'm missing something. If this is proper and if it works why do so many people use the clearfix hack? Maybe I'm missing something obvious?

DR01D
  • 1,325
  • 15
  • 32

1 Answers1

3

Yes, it's correct. Floating takes the element out-of-flow in a special way, and clearing pushes the element below previous floats.

This is not a replacement of the clearfix hack because a cleared float is still out-of-flow, and thus the parent element won't grow to encompass it (unless it establishes a block formatting context). See Floating elements within a div, floats outside of div. Why? for more information.

div {
  border: 2px solid blue;
  margin-bottom: 50px;
}
span {
  float: left;
  clear: both;
  background: yellow;
}
.clearfix::after {
  content: '';
  display: block;
  clear: both;
}
No clearfix:
<div>
  <span>Float</span>
  <span>Float</span>
  Text
</div>
With clearfix:
<div class="clearfix">
  <span>Float</span>
  <span>Float</span>
  Text
</div>
Community
  • 1
  • 1
Oriol
  • 274,082
  • 63
  • 437
  • 513
  • You might bold the "previous floats" part. I'm betting some think that really is a substitute. – Rob Jan 30 '17 at 18:18
  • I'm dissecting your amazingly helpful comment in [Floating elements within a div, floats outside of div. Why?](http://stackoverflow.com/questions/2062258/floating-elements-within-a-div-floats-outside-of-div-why). I plan to spend the rest of the day (and possibly much of tomorrow) tearing apart your examples in Dreamweaver. I'm going to fully understand this before I move on. The basics of float and clear are easy but understanding the root fundamentals is mind-boggling. – DR01D Jan 30 '17 at 19:23