Bootstrap clearfix class with example
In this article, I will show you how you can clear floated space and start new elements from new line.
If you use float property to element, it always float to left or right as you have set. The new elements you may want to start from new line but it may also start in beside floated elements. Here is below example.
Example:
<!doctype html>
<html>
<head>
<title>Without clearfix</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="border border-3">
<img src="https://hackthestuff.com/uploads/subCategories/1626256775898nginx.png" class="float-start">
<h1>Without clearfix</h1>
</div>
<p class="lead">This is new line and should start from new line.</p>
</div>
</body>
</html>
You can see <p> element is started after <h1> element which is not as you want. To prevent <p> element start direct after <h1> element, you need to clear the float. Bootstrap .clearfix class clear floated content within a parent element.
You just need to add .clearfix class to the parent element and it will fix the issue. Here is the example:
<!doctype html>
<html>
<head>
<title>With clearfix</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="border border-3 clearfix">
<img src="https://hackthestuff.com/uploads/subCategories/1626256775898nginx.png" class="float-start">
<h1>With clearfix</h1>
</div>
<p class="lead">This is new line and should start from new line.</p>
</div>
</body>
</html>
You can see p element started after clearfix class. I hope it will help you.