How to clear floats with the clearfix?
The clearfix is a way for an element to clear or fix its child element automatically. It is used with a float layout where elements are stacked horizontally. For example, When we place an image just next to some contents, there are chances that the two contents overlap each other. We can remove it using clearfix.
Clearing float with clearfix class
When we have a floating element larger than its container. It will overflow the container. To fix this overflow use overflow: auto
within clearfix
class.
Example: Clearing float with the overflow property
In this example, We used two images, one is using clearfix and the other is without it. You can see the difference between both and understand the importance of clearfix.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
div {
border: 2px solid ;
padding: 8px;
width: 300px;
}
.img1 {
float: right;
width: 150px;
height: 150px;
}
.img2 {
float: right;
width: 150px;
height: 150px;
}
.clearfix {
overflow: auto;
}
</style>
</head>
<body>
<div>
<h2> Contents without clearfix</h2>
<img class="img1" src="https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/tutorials/uploads/pictures/1627294057-101156.png" alt="image1">
The image is floats at right. The image overflows the content.
</div>
<div class="clearfix">
<h2> contents with clearfix</h2>
<img class="img2" src="https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/tutorials/uploads/pictures/1627294057-101156.png" alt="image2">
So here we fixed the overflow of the image using clearfix.
</div>
</body>
</html>
Output:
Here is the output of the above program.
![clear float](LAZY_IMG_PLACEHOLDER)
Example: Clearing float with content, clear and display properties
In this example, we will use clear: both to remove the left and right floating properties. The clearfix
class is added with ::after
pseudo class. Further display:table
property is used. It is supported in all the latest versions.
Conclusion
In this tutorial, we have learned to use clearfix to clear floating so that the elements do not overlap with each other. We can use the overflow property or use a modern clearfix hack using the display and other properties.