Responsive Fix! Clearing Floats with clearfix method

What actually is clearfix? Here is some examples of a layout with clearfix, compared to a layout without clearfix?


The scenario: span float:left; and span float:right; are floated side by side inside a div element, and there’s a main div element after div.

The desired outcome: We want div to expand to the height of its child elements and we want (main div) to be after div .

The actual outcome: div collapses and takes on no height at all, as if there is nothing inside it, putting main div in an undesired location and potentially causing any backgrounds or borders on div to be missing.

Method 1: A clearfix is performed as follows:
.clearfix:after {
   content: " "; /* Older browser do not support empty content */
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

Or, if you don't require IE<8 support, the following is fine too:

.clearfix:after {
  content: "";
  display: table;
  clear: both;
}
Method 2:   You don't have to use clearfix in this case .
.shape1 {
display :inline ;
width: 200px;
  height: 100px;
  margin: 1em;
}


You have to do extra work for IE6 and IE7 support of inline-block. Sometimes people talk about inline-block triggering something called hasLayout, though you only need to know about that to support old browsers.

 If you want support for older browsers, it's best to use this clearfix :

.clearfix:before, .clearfix:after {
    content: "";
    display: table;
}

.clearfix:after {
    clear: both;
}

.clearfix {
    *zoom: 1;
}

Method 3:The Overflow Way
Using the overflow property on our div element, we can actually force the div to expand to the height of the floated elements. Our CSS will look like this:

.clearfix {
  overflow: hidden; /* can also be "auto" */
}

Method 4: In rule in w3c specification 
Added a new value to the min-height property , in order to help solve this problem. It looks like this:

.clearfix {
  min-height: contain-floats;
}

No comments:

Post a Comment