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
Clearfix Bootstrap class
The Bootstrap .clearfix class solves the common issue of parent containers collapsing when all child elements are floated. It ensures the parent container properly wraps around its floated children.
What is Clearfix?
When elements are floated using .pull-left or .pull-right, they are removed from the normal document flow. This can cause their parent container to have zero height, leading to layout problems. The .clearfix class forces the parent to expand and contain its floated children.
Example
Here's how to use the .clearfix class to properly contain 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: #58D3F7; padding: 10px;">
Quick Float to left
</div>
<div class="pull-right" style="background: #DA81F5; padding: 10px;">
Quick Float to right
</div>
</div>
</body>
</html>
Without Clearfix vs With Clearfix
To understand the importance of clearfix, here's a comparison:
| Without .clearfix | With .clearfix |
|---|---|
| Parent container collapses (height: 0) | Parent container wraps around floated children |
| Background/borders may not display properly | Background/borders display correctly |
| Layout breaks in complex designs | Layout remains stable |
How It Works
The .clearfix class uses CSS pseudo-elements to create invisible content that clears the float:
.clearfix::after {
content: "";
display: table;
clear: both;
}
Common Use Cases
- Creating layouts with floated sidebars and content areas
- Building card layouts with floated elements
- Fixing collapsed containers in grid systems
- Ensuring proper spacing between sections with floated content
Bootstrap 4+ Alternative
In Bootstrap 4 and later versions, flexbox utilities like .d-flex are preferred over floats for most layouts, but .clearfix remains useful for legacy code and specific float-based designs.
Conclusion
The Bootstrap .clearfix class is essential for containing floated elements and preventing parent container collapse. Use it whenever you have floated children that need proper containment within their parent.
