Float and Clear in CSS

Float and Clear in CSS | Web Development

In this article, we will learn about the float and clear property of CSS.

Float Property

The float property is basically a positioning property in CSS used to specify that how an element will float. It is used to position and format the content.

It can have the following values:

  • none: In this the element does not float and appears as it is. It is the default value.
  • right: the element will float to right in its container.
  • left: the element will float to left in its container.
  • inherit: In this the element inherits the float property from its parent.

Generally, It is used to wrap content around the images.

Let’s take an example to understand it in a better way:

For Example:

  1. float: left
img {
     float: left;
     }

Output:

Float left

2. float: right

img {
     float: right;
     }

Output:

3. Without float

img {
     float: none;
     }

Output:

4. With float next to each other

div {
     float: left;
     padding: 10px;
     }

#div1 {
       background-color: green;
       }

#div2 {
       background-color: blue;
       }

#div3 {
       background-color: yellow;
       }

#div4 {
       background-color: red;
       }

Output:

 With float next to each other

Clear Property

The Clear property is used to control the flow of floated elements. Basically, It specifies that what will happen to the element next to the floated element.

It can have the following values:

  • none: The clear property doesn’t exist in this. This is default value.
  • left: It controls the flow of left floated elements and the element is pushed below left floated element.
  • right: It controls the flow of right floated elements and the element is pushed below right floated element.
  • both: It controls the flow of both side floated elements and the element is pushed below both left and right floated element.
  • inherit: inherits the clear property from its parent element.

The Clearfix Hack

Sometimes the floated element is taller than the element containing it. then, the floated element will overflow outside the container. So we can add the clearfix hack to solve this problem.

For Example:

.clearfix {
           overflow: auto;
           }

Output:

That’s all about the float and clear in CSS.

Hope this article will guide you to recognize all about Float and Clear in CSS that you needed and still if you have any problem or queries regarding this, post them in the comments section and we will be glad to assist you.

This Post Has One Comment

Leave a Reply