Clearing Floats

CSS examples on different approaches to clear floats

by Ivan Sim

HTML

<h2>Notice how the parent container border is not stretched to accomodate the floating children containers</h2>
<div class="parent-container">
  <div class="left-container first-child-container">Left Container</div>
  <div class="right-container second-child-container">Right Container</div>
</div>

<h2>1. Using <span class="css-property">overflow</span></h2>
<div class="parent-container overflow">
  <div class="left-container first-child-container">Left Container</div>
  <div class="right-container second-child-container">Right Container</div>
</div>

<h2>2. Using <span class="css-property">width</span></h2>
<div class="parent-container left-container full-width">
  <div class="left-container first-child-container">Left Container</div>
  <div class="right-container second-child-container">Right Container</div>
</div>

<h2>3. Using <span class="css-property">clear:both</span></h2>
<div class="parent-container">
  <div class="left-container first-child-container">Left Container</div>
  <div class="right-container second-child-container">Right Container</div>
    <div class="clear-floats"></div>
</div>

<h2>4. Using <span class="css-property">:after</span> pseudo-class</h2>
<div class="parent-container clear-floats-after">
  <div class="left-container first-child-container">Left Container</div>
  <div class="right-container second-child-container">Right Container</div>
</div>

CSS

div.parent-container{
  border:3px solid lightgray;
  margin-bottom:30px;
}

div.left-container{
  float:left;
}

div.right-container{
  float:right;    
}

div.first-child-container{
  background-color:yellow;
  width:50%;
}

div.second-child-container{
  background-color:green;
  width:50%;
}

span.css-property{
  font-style:italic;   
}

div.overflow{
  overflow:hidden;
}

div.full-width{
  width:100%;   
}

div.clear-floats{
  clear:both;
}

div.clear-floats-after:after{
  content:" ";
  display:block;
  height:0;
  clear:both;
  visibility:hidden;
}