Clearing floats: the Advanced Version
Most medium-complex sites involve floating elements to put them side-by-side. Often we want elements that follow floated elements not to be affected by them. Here are the top three ways to deal with clearing floats.
Using a dedicated .clear
class
HTML
<p class="clear">Some text that follows some floats elements</p>
CSS
.clear {
clear:both;
}
Using a dedicated .clearfix
class to make a container “self-clearing”
HTML
<ul id="gallery" class="clearfix">
<li><a href="#"><img src="image.jpg" alt="Image" /></a></li>
<li><a href="#"><img src="image.jpg" alt="Image" /></a></li>
<li><a href="#"><img src="image.jpg" alt="Image" /></a></li>
</ul>
CSS
#gallery li {
float:left;
}
.clearfix:after {
content: ".";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
For those scoring at home, the idea is to use the :after
pseudo-class to insert the period character (.), set it to display:block
, clear any floats, and then hide that extra character. Clever.