CSS Clearfix Technique

CSSCSSBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn about the clearfix technique in CSS. This technique is used to ensure that an element clears its floated children. We will explore how to implement this technique in our code and discuss its limitations. By the end of this lab, you will have a solid understanding of how to use clearfix in your CSS layouts.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL css(("`CSS`")) -.-> css/BasicConceptsGroup(["`Basic Concepts`"]) css(("`CSS`")) -.-> css/CoreLayoutGroup(["`Core Layout`"]) css(("`CSS`")) -.-> css/IntermediateStylingGroup(["`Intermediate Styling`"]) css/BasicConceptsGroup -.-> css/selectors("`Selectors`") css/CoreLayoutGroup -.-> css/margin_and_padding("`Margin and Padding`") css/CoreLayoutGroup -.-> css/display_property("`Display Property`") css/IntermediateStylingGroup -.-> css/pseudo_elements("`Pseudo-elements`") subgraph Lab Skills css/selectors -.-> lab-35182{{"`CSS Clearfix Technique`"}} css/margin_and_padding -.-> lab-35182{{"`CSS Clearfix Technique`"}} css/display_property -.-> lab-35182{{"`CSS Clearfix Technique`"}} css/pseudo_elements -.-> lab-35182{{"`CSS Clearfix Technique`"}} end

Clearfix

index.html and style.css have already been provided in the VM.

To ensure that an element self-clears its children when using float to build layouts, you can use the ::after pseudo-element and apply content: '' to allow it to affect layout. Additionally, use clear: both to make the element clear past both left and right floats. However, this technique only works properly if there are no non-floating children in the container and there are no tall floats before the clearfixed container but in the same formatting context (e.g. floated columns). For example:

<div class="clearfix">
  <div class="floated">float a</div>
  <div class="floated">float b</div>
  <div class="floated">float c</div>
</div>
.clearfix::after {
  content: "";
  display: block;
  clear: both;
}

.floated {
  float: left;
  padding: 4px;
}

Note that using a more modern approach, such as the flexbox or grid layout, is recommended over using float to build layouts.

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Clearfix lab. You can practice more labs in LabEx to improve your skills.

Other CSS Tutorials you may like