How to clear floats with the \"clearfix\" hack with CSS?

The floats in CSS defines how an element should float. Let?s say, an element is taller than the element containing it. If it is floated, it will overflow outside of its container. Therefore, it?s hack is to use the overflow property and set the value auto.

Without Clearfix

Let us understand the issue by running the following program. Clearly, overflow occurs and the image moves outside −

Example

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      }
      div {
         border: 3px solid rgb(21, 0, 114);
         padding: 5px;
      }
      img {
         float: right;
      }
   </style>
</head>
<body>
   <h1>Without Clearfix</h1>
   <div>
      <img src="https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg" width="100" height="100"/>
      Sample Text
   </div>
</body>
</html>

With Clearfix

In this example, we will see the fix to clear floats using the clearfix. Let us begin with an image in the div container.

Set the div

Set an image inside the div −

<div class="clearfix">
   <img src="https://www.tutorialspoint.com/plsql/images/plsql-mini-logo.jpg" width="100" height="100"/>
   Sample Text
</div>

Set the Image

The image is set on the right for our example −

img {
	float: right;
}

Fix With Clearfix

We have set the overflow property with the value auto to fix the issue. Now the image will get fit inside the container −

.clearfix {
   overflow: auto;
}

Example

To clear floats with the clearfix hack using CSS, the code is as follows −

<!DOCTYPE html>
<html>
<head>
   <style>
      body {
         font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
      }
      div {
         border: 3px solid rgb(21, 0, 114);
         padding: 5px;
      }
      img {
         float: right;
      }
      .clearfix {
         overflow: auto;
      }
   </style>
</head>
<body>
   <h1>With Clearfix</h1>
   <div class="clearfix">
      <img src="https://www.tutorialspoint.com/plsql/images/plsql-mini-logo.jpg" width="100" height="100"/>
      Sample Text
   </div>
</body>
</html>
Updated on: 2023-11-16T16:17:10+05:30

115 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements