How do I use the css float property?



  • Note: Other CSS methods are now more commonly used to perform functions previously performed using float.

    We will start off by using a template CSS/HTML with a container and two boxes to demonstrate float.

    HTML

    ...
       <div class="container">
           <div class="left"></div>
           <div class="right"></div>
       </div>
    ...
    

    CSS

    ...
     .container {
               background-color: burlywood;
           }
    
           .left {
               background-color: darkcyan;
               height: 100px;
               width: 100px;
           }
    
           .right {
               background-color: darkgoldenrod;
               height: 100px;
               width: 100px;
           }
    ...
    

    The result is:
    3c8c9a11-d6c0-479c-bd02-5ea4d77fcc6e-image.png

    Adding the css float property to the left box.

    ...
    .left {
               background-color: darkcyan;
               height: 100px;
               width: 100px;
               float: left;
           }
    ...
    

    The result is:

    376f7ec3-c85a-42a7-9331-b7ee24af4ee9-image.png

    The orange box is behind the green. The left box jump out of the normal flow of the page.

    Adding the css float property to the left box.

    ...
    .right{
               background-color: darkgoldenrod;
               height: 100px;
               width: 100px;
               float: right;
           }
    ...
    

    The result is:
    98e08755-b10c-4a0c-a06e-5efb6d0833ba-image.png

    The background color of the container has disappeared or rather it is exactly there but zero pixels. We can add a wider border with a color to show this.

    ...
     .container {
               background-color: burlywood;
               border-top: 10px solid rebeccapurple;
               border-bottom: 10px solid goldenrod;
           }
    ...
    

    The result is:
    dedcda08-2cc1-42f2-af7d-3b985f81937c-image.png

    The container has jumped out of the normal flow of the page to resolve this there are three methods.

    Add the overflow CSS property to the CSS container using the value auto

    ...
    overflow: auto;
    ...
    

    The result is:
    4c30513f-580e-4fed-bc6a-57101dff661c-image.png

    Another way is to create another div element and assign it class clear.

    ...
    <div class="clear"></div>
    ...
    

    Add the CSS for class clear.

    ...
    .clear {
      clear: both;
    }
    ...
    

    Lastly you can add another class to the container, called clearfix, then add the following CSS

    ...
    <div class="container clearfix">
    ...
    
    ...
    .clearfix::after {
               content: "";
               display: block;
               clear: both;
           }
    ...
    

Log in to reply
 

© Lightnetics 2024