Lesson 24 of 40 · 2 min
Clearfix
Clearfix in CSS: Learn how to prevent layout issues with floated elements by ensuring proper container height using clearfix techniques.
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>
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.
More from CSS Tutorial
- Lesson 26 · 2 minCSS resizeLearn about the CSS ‘resize’ property for interactive element resizing, enhancing user experience and layout control in web design.
- Lesson 27 · 3 minQuotesExplore different quotation mark characters, from straight quotes to curly and language-specific marks, used to indicate quoted speech in written…
- Lesson 28 · 4 minOrderCSS ‘order’ property: Control the visual order of flexbox and grid elements for responsive and customized layouts in web design.