You are here:Home » CSS » Cross browser css float clearing

Cross browser css float clearing

Solution 1: The :after Pseudo-Element (Best one)

The :after pseudo-element adds an element to the rendered HTML page. This method has been used quite extensively to resolve float-clearing issues. Here is how the CSS looks:



.clearfix:after {
    content: ".";
    display: block;
    height: 0;
    clear: both;
    visibility: hidden;
}
 
The CSS class “clearfix” is applied to any container that has floating children and does not expand to enclose them.
But this method does not work in Internet Explorer up to version 7, so an IE-only style needs to be set with one of the following rules:

.clearfix {
 display: inline-block;
}

.clearfix {
 zoom: 1;
}
 
Depending on the type of issue you’re dealing with, one of the above two
 solutions will resolve the issue in Internet Explorer. It should be 
noted that the zoom property is a non-standard Microsoft proprietary property,
 and will cause your CSS to become invalid. 

Solution 2: New element with a clear: both option.(Old one)

This is an outdated method, but is an easy option. Simply add an extra element at the bottom of the container and “clear” it. Here’s how the HTML would look after this method is implemented:

<div>
    <div style="float: left">Some floated text</div>
    <p>Some unfloated text</p>

  <div style="clear: both"></div>
</div>
</div>

Solution 3: Overflow Property

By far the best, and easiest solution to resolve the collapsing parent issue is to add overflow: hidden or overflow: auto to the parent element. It’s clean, easy to maintain, works in almost all browsers, and does not add extra markup.
You’ll notice I said “almost” all browsers. This is because it does not work in IE6. But, in many cases, the parent container will have a set width, which fixes the issue in IE6. If the parent container does not have a width, you can add an IE6-only style with the following code:

// This fix is for IE6 only
.clearfix {
 height: 1%;
 overflow: visible;
}
 
In IE6, the height property is incorrectly treated as min-height, so this forces the container to enclose its children. The overflow property is then set back to “visible”, to ensure the content is not hidden or scrolled.
The only drawback to using the overflow method (in any browser) is the possibility that the containing element will have scrollbars or hide content. If there are any elements with negative margins or absolute positioning inside the parent, they will be obscured if they go beyond the parent’s borders, so this method should be used carefully. It should also be noted that if the containing element has to have a specified height, or min-height, then you would definitely not be able to use the overflow method.
So, there really is no simple, cross-browser solution to the collapsing parent issue. But almost any float clearing issue can be resolved with one of the above methods.

0 comments:

Post a Comment