CSS Clearfix

The clearfix is a common CSS hack used to clear floated elements. When elements are floated, the parent container may collapse and not wrap around the floated elements. Clearfix is used to solve this issue by forcing the container to expand and clear its floated child elements.

Key Points on CSS Clearfix:

Syntax for CSS Clearfix:

Syntax Example

/* Clearfix syntax */
        .clearfix::after {
            content: "";
            display: table;
            clear: both;
                         }

Examples of CSS Clearfix:

The following examples demonstrate the usage of clearfix:

Code Example: Basic Clearfix


        .container {
        display: block;
                   }
        
        .container::after {
        content: "";
        display: table;
        clear: both;
                          }

Output

Box 1
Box 2

Code Example: Clearfix with Nested Floats


            .clearfix::after {
            content: "";
            display: table;
            clear: both;
                            }
        
           .container {
            width: 100%;
            overflow: hidden;
                     }
        
            .box {
            width: 45%;
            float: left;
            margin: 10px;
                }

Output

Box 1
Box 2

Common Clearfix Properties:

To ensure a smooth layout when using floated elements, apply clearfix to the parent container. This ensures that the layout remains consistent, and the parent container will contain the floated children properly.