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
How to clear floats with the \"clearfix\" hack with CSS?
The clearfix hack in CSS is used to fix the issue where floated elements overflow outside of their container. When an element is floated and is taller than its container, it can break the layout by extending beyond the container's boundaries.
Syntax
.clearfix {
overflow: auto;
}
Without Clearfix
Let us understand the issue by running the following program. The floated image overflows outside its container −
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.container {
border: 3px solid rgb(21, 0, 114);
padding: 5px;
margin: 10px;
}
img {
float: right;
margin: 5px;
}
</style>
</head>
<body>
<h2>Without Clearfix</h2>
<div class="container">
<img src="/mysql/images/mysql-mini-logo.jpg" width="100" height="100"/>
Sample Text - This container doesn't contain the floated image properly.
</div>
</body>
</html>
A container with blue border containing text and a floated image. The image overflows outside the container boundary, causing layout issues.
With Clearfix
The clearfix hack uses the overflow: auto property to force the container to expand and contain the floated elements properly −
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.container {
border: 3px solid rgb(21, 0, 114);
padding: 5px;
margin: 10px;
}
img {
float: right;
margin: 5px;
}
.clearfix {
overflow: auto;
}
</style>
</head>
<body>
<h2>With Clearfix</h2>
<div class="container clearfix">
<img src="/plsql/images/plsql-mini-logo.jpg" width="100" height="100"/>
Sample Text - This container properly contains the floated image using clearfix.
</div>
</body>
</html>
A container with blue border that properly contains both the text and the floated image. The container expands to accommodate the image height, preventing overflow.
How It Works
The overflow: auto property creates a new block formatting context, which forces the parent container to recognize and contain all floated child elements within its boundaries.
Conclusion
The clearfix hack with overflow: auto is a simple solution to contain floated elements within their parent containers. This prevents layout issues caused by floated elements overflowing their containers.
