Friday, November 12, 2010

Clearfix for floats

When you use float on an element other styles like background color may not apply on it. So to workaround this problem we can create a class called clearfix. This class can be applied to all element containing floating elements.
for example consider this piece of xhtml code

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Testing Clearfix</title>
    <style type="text/css">
 body
        {
            font13px/1.5em Tahoma;
        }
          .h-menu li         {             floatleft;             displayblock;             width100px;         }         .h-menu         {             backgroundRed;         }     </style> </head> <body>     <ul class="h-menu">         <li>Home</li>         <li>Members</li>         <li>About</li>         <li>Contact</li>     </ul> </body> </html> 

Well the background color of menu should be red but due to float the height of ul will be zero so we after clearfix to cancel the effect of floats and get the result we want.

/* ----- clear fix for floats ----- */
        .clearfix:after
        {
            content".";
            displayblock;
            height0;
            clearboth;
            visibilityhidden;
        }
        .clearfix
        {
            displayinline-block;
        }
        /* hides clearfix from IE-mac \*/
        * html .clearfix
        {
            height1%;
        }
        .clearfix
        {
            displayblock;
        }
        /* end hide from IE-mac */

After applying clearfix

<ul class="h-menu clearfix">
        <li>Home</li>
        <li>Members</li>
        <li>About</li>
        <li>Contact</li>
    </ul>
 

No comments:

Post a Comment