CSS Float

The float property in CSS is used to position an element to the left or right of its container, allowing text and inline elements to wrap around it. Originally designed for wrapping text around images, float can also be used to create various layouts and effects.

Float property values

1. none: The element does not float. This is the default value.

2. left: The element floats to the left of its container.

3. right: The element floats to the right of its container.

4. inherit: The element inherits the float value from its parent.

Syntax:


selector {
    float: none | left | right | inherit;
}

Example:


<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        .container {
            border: 1px solid #000;
            padding: 10px;
        }
        .box {
            width: 100px;
            height: 100px;
            margin: 10px;
            background-color: lightblue;
        }
        .left {
            float: left;
        }
        .right {
            float: right;
        }
        .clearfix::after {
            content: "";
            display: table;
            clear: both;
        }
    </style>
</head>
<body>

    <div class="container clearfix">
        <div class="box left">Float Left</div>
        <div class="box right">Float Right</div>
        <p>This is some text that wraps around the floating elements. The float property can be used to create simple layouts where elements are positioned to the left or right and content flows around them.</p>
    </div>

</body>
</html>

Try it Yourself

Float Left
Float Right

This is some text that wraps around the floating elements. The float property can be used to create simple layouts where elements are positioned to the left or right and content flows around them.

In this example:

  • The .box.left element floats to the left, and the .box.right element floats to the right.
  • The text inside the .container wraps around the floating elements.
  • The .clearfix class is used to clear the floats, ensuring that the container expands to encompass the floated elements. This is a common technique to avoid layout issues when using floats.

Notes:-

Clearing Floats: Floats can cause layout issues because they are taken out of the normal document flow. To ensure that a container expands to fit floated elements, you need to clear the floats. This can be done using the clear property or the clearfix method.

Syntax:


selector {
    clear: both;
}