Float

Other pages on this site mention using floats. Specifically the page on columns:

This page compiles some rules and resources on using floats.

Here are the basic rules/facts/issues you should learn about Floats:

  1. You can only float Block level elements (see why I wanted you to memorize that stuff).
  2. When you float something your float it to either the left or right side of the page.
    #content{
        float:left;
    }
    #sidebar{
        float:right;
    }
  3. you need to specify the width of an item if you are going to float it.
    #content{
        float:left;
        width:600px;
    }
  4. Once you float an element all of the block elements after it will also be floated until you give one of them a clear property.
    #content{
        float:left;
        width:600px;
    }
    #sidebar{
        float:right;
    }
    #footer{
        clear:right; /*you can also clear:left or if floated both ways clear:both */;
    }
  5. When you float an element it removes itself from the normal flow of the page layout. Take this for example, a div with two paragraphs inside of it:
    <div>
    <p>one</p>  <p>two</p>
    </div>

    Let’s add this css to it:

    
    div{
         background-color:red;
         width:400px;
    }
    p{
         margin: 20px;
         padding: 20px;
         width: 50px;
         height:50px;
         background-color:yellow;
         border: 1px solid #999;
    }
    


    And we get this:

    If you float the paragraphs then the div won't realize they are there. Here's the CSS:

    div{
     background-color:red;
     width:400px; 
    }
    
    p{
     margin: 20px;
     padding: 20px;
     width: 50px;
     height:50px;
     background-color:yellow;
     border: 1px solid #999;
     float:left;
    }

    And here's how it looks.

    The red is gone because the div element now thinks it doesn't have any content in it so it has no height. To solve the problem we can add what is often called a clearfix or clearing div. It's basically an empty div we add after the floated elements but inside of the containing element. There are other fixes, see this page and scroll down to the answer by Paul O'B for a run down on the other methods and the drawbacks.

    Here's the HTML

    <div>
    <p>one</p>  <p>two</p>
    <div class="clearfix"></div>
    </div>

    And here's the CSS to go along with it

    .clearfix{
     clear:both;
    }

    And here's the result

Resources:

CSS Max Design FLoat Tutorial — this tutorial shows how to use floats in a variety of situations, from floating single images inside of text to two drop caps and two- and three-column layouts.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>