w3resource

HTML-CSS: Clearfix

HTML-CSS : Exercise-17 with Solution

Using HTML, CSS ensures that an element self-clears its children.

  • Use the :after pseudo-element and apply content: '' to allow it to affect layout.
  • Use clear: both to make the element clear past both left and right floats.
  • For this technique to work properly, make sure there are no non-floating children in the container and that there are no tall floats before the clearfixed container but in the same formatting context (e.g. floated columns).
  • Note: This is only useful if you are using float to build layouts. Consider using a more modern approach, such as the flexbox or grid layout.

HTML Code:

<!--License: https://bit.ly/3GjrtVF-->
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>Using HTML, CSS ensures that an element self-clears its children</title>
</head>
<body>
<div class="clearfix">
  <div class="floated">1st Item </div>
  <div class="floated">2nd Item </div>
  <div class="floated">3rd Item </div>
</div>
</body>
</html>

CSS Code:

<style> 
.clearfix:after {
  content: '';
  display: block;
  clear: both;
}

.floated {
  float: left;
  padding: 4px;
}
</style>

HTML-CSS Editor:

See the Pen html-css-practical-exercises by w3resource (@w3resource) on CodePen.


What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Share this Tutorial / Exercise on : Facebook and Twitter

HTML-CSS: Tips of the Day

How to get CSS to select ID that begins with a string ?

[id^=product]

^= indicates "starts with". Conversely, $= indicates "ends with".

The symbols are actually borrowed from Regex syntax, where ^ and $ mean "start of string" and "end of string" respectively.

Ref: https://bit.ly/3rSZ2t7