Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 9 - Positioning And Layout

9.2 Float And Clear Properties

The float property allows you to position elements to the left or right within their container, while the clear property ensures proper alignment of subsequent elements.

  1. Float The float property enables you to wrap text around an element or create a column layout within its container.

    <style>
      div {
        float: right;
        width: 50%;
      }
    </style>
    <div>This is a DIV element floated to the right.</div>
    

    In this example, the div element is floated to the right within its container, taking up 50% of the container's width.

  2. Clear The clear property prevents elements from wrapping around floated elements by specifying which sides of an element need to be clear of floats.

    <style>
      .left {
        float: left;
        width: 50%;
        background-color: lightblue;
      }
      .right {
        float: right;
        width: 50%;
        background-color: lightgreen;
      }
      .clear {
        clear: right;
      }
    </style>
    <div class="left">This is a left-floated element.</div>
    <div class="right">This is a right-floated element.</div>
    <div class="clear">This paragraph appears below the floated elements due to the clear property.</div>
    

    Here, the .clear class ensures that the paragraph appears below both the left-floated and right-floated elements.