Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Clear the float of an element with Bootstrap
To clear the float of an element in Bootstrap, use the .clearfix class. This utility class ensures that a container properly wraps around its floated child elements, preventing layout issues.
What is Float Clearing?
When elements are floated (using float: left or float: right), their parent container may collapse because floated elements are taken out of the normal document flow. The .clearfix class solves this by forcing the parent to contain its floated children.
Example
Here's how to use Bootstrap's .clearfix class to clear floated elements:
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Clearfix Example</title>
<link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<script src="/scripts/jquery.min.js"></script>
<script src="/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class="clearfix" style="background: orange; border: 1px solid #000; padding: 10px;">
<div class="pull-left" style="background: blue; color: white; padding: 5px;">
Left floated content
</div>
<div class="pull-right" style="background: blue; color: white; padding: 5px;">
Right floated content
</div>
</div>
<p style="margin-top: 20px;">The orange container properly wraps around both floated elements.</p>
</body>
</html>
Without Clearfix
Here's what happens when you don't use .clearfix:
<!DOCTYPE html>
<html>
<head>
<title>Without Clearfix</title>
<link href="/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div style="background: orange; border: 1px solid #000; padding: 10px;">
<div class="pull-left" style="background: blue; color: white; padding: 5px;">
Left floated content
</div>
<div class="pull-right" style="background: blue; color: white; padding: 5px;">
Right floated content
</div>
</div>
<p style="margin-top: 20px;">The orange container collapses without clearfix.</p>
</body>
</html>
Alternative Approaches
Besides .clearfix, you can also use:
-
.rowand.col-*classes for grid-based layouts -
overflow: autooroverflow: hiddenon the parent container - Flexbox utilities like
.d-flexfor modern layouts
Conclusion
Bootstrap's .clearfix class is essential for managing floated layouts. It ensures parent containers properly contain their floated children, preventing layout collapse and maintaining design integrity.
