CSS – Clearfix

By Published 2 min read

Certainly! In CSS, a “clearfix” is a technique used to solve a common layout issue that arises when working with floated elements. Floats are often used to create multi-column layouts, but they can lead to unexpected behavior when their parent container doesn’t properly encompass their height. This is where clearfix comes into play.

Imagine you have a container with several floated elements inside it, and those elements have different heights. Without clearfix, the container may not expand to enclose the tallest floated element, which can lead to layout problems where content appears to “overflow” or is misaligned.

To address this issue, you can use a clearfix. A clearfix is typically applied to the container element, and it ensures that the container expands to the proper height, accommodating all of its floated children.

Here’s an example of how you might apply clearfix in CSS:

<!DOCTYPE html>
<html>
<head>
<style>
  /* Style for the container with floated elements */
  .container {
    border: 1px solid #ccc;
  }

  /* Style for the floated elements */
  .float-left {
    float: left;
    width: 50%;
  }

  /* Clearfix to ensure proper container height */
  .clearfix::after {
    content: "";
    display: table;
    clear: both;
  }
</style>
</head>
<body>

<div class="container clearfix">
  <div class="float-left">Content 1<br>Content 1<br>Content 1</div>
  <div class="float-left">Content 2<br>Content 2</div>
</div>

</body>
</html>Code language: HTML, XML (xml)

Output :

Without.clearfix::after rule output like this :

With the .clearfix::after rule output like this :

In this example, the .clearfix::after rule is added to the container, and it uses the clear: both; property to ensure that the container expands to include the floated elements inside it.

Clearfix is a valuable technique for maintaining the integrity of your webpage’s layout when working with floated elements. It ensures that your containers adjust their height to accommodate the content correctly, preventing unexpected layout issues.

Khan Waseem is a tech lead and full-stack engineer in Bengaluru, building hospitality and SaaS software with Node.js, React and React Native. See the resume