0

From what I gather if you have a floated item in a parent container that is too small for it, then some sort of problem arises. All the documentation on this is vague and unclear. Can someone explain in a concise way what is the purpose of clearing floats, and what is the consequence of not doing it?

chopper draw lion4
  • 12,401
  • 13
  • 53
  • 100
  • http://css-tricks.com/the-how-and-why-of-clearing-floats/ – BenM Nov 28 '14 at 07:14
  • possible duplicate of [How does CSS float work? Why doesn't the height of a container element increase if it contains floated elements?](http://stackoverflow.com/questions/16568272/how-does-css-float-work-why-doesnt-the-height-of-a-container-element-increase) – Vitorino fernandes Nov 28 '14 at 07:15

2 Answers2

2

In short,

When you float elements on a page sometimes there is space left over in the dom. Elements under the floated elements will try to take that space. If you clear the float on the element under the floated elements it says HEY WE DON'T WANT TO TAKE THAT SPACE, WE WANT OUR OWN SPACE.

for example imagine this is a page

I have 3 elements |, |, |

if I put them in the document it will output like this

|
|
|

if I float them left I get this

|||

if I want to clear the float on the last | we get

||
|
Rafael
  • 7,605
  • 13
  • 31
  • 46
-1

For example check out the below code

<div class="parent">
   <div class="first-child">
      <p>Im floated left</p>
   </div>
  <div class="second-child">
      <p>Im floated left</p>
   </div>

</div>

<div class="occupy-spaceleft">
  will occupy the remaning space if the parent div has not cleared the float or else if the float is cleared means . This div will come below the parent div
</div>

here is the best clearfix code for clearing the floats

.clearfix:before,
.clearfix:after {
    content: "";
    display: table;
} 
.clearfix:after {
    clear: both;
}
.clearfix {
    zoom: 1; /* For IE 6/7 (trigger hasLayout) */
}

now just include clearfix class to parent

<div class="parent clearfix">
       <div class="first-child">
          <p>Im floated left</p>
       </div>
      <div class="second-child">
          <p>Im floated left</p>
       </div>

    </div>

here is the link JSFIDDLE

Adarsh Gowda K R
  • 941
  • 8
  • 15