Solving CSS Float’s Problem

As a web designer, we always see a problem happened when a floated element is within a container div, the floated element doesn’t automatically increase the height of the container. The main reason causing this problem is the container doesn’t contains the floated element anymore, when the element is floated.

Still not understand what I’m talking about? No worries, let’s take a look on the picture below:

Float Problem
This is one of the common problem happened when using css float.

The Solution To Fix CSS Float’s Problem

Ok, here is the technique that we used to solve the problem that caused by CSS float:
[html highlight=”17,18-24,29″]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Solving CSS Float’s Problem</title>
<style type="text/css">
.parent {
background: #FC0;
}
.right {
float: right;
}
.left {
float: left;
}

.clearfix:before,
.clearfix:after {
content: " ";
display: block;
}
.clearfix:after {
clear: both;
}
</style>
</head>

<body>
<div class="parent clearfix">
<div class="right">Right Element</div>
<div class="left">Left Element</div>
</div>
</body>
</html>
[/html]

As you can see the :before and :after pseudo-elements has been used to address the problem. These pseudo-elements does exactly what the word implies. It creates a phoney element and inserts it before and after the content of the element that we’ve specified.

In this case, we insert a blank space before and after the parent div; and clear any float elements at the end of parent div.

Pretty simple right? Share this if you found this information helpful.

*Update

We need extra declaration to fix the CSS float’s problem in IE6 & IE7:
[css]
.clearfix{ *zoom:1; }
[/css]
*Thank you for this tips Michael Shen!


Posted

in

by

Post’s tag:

Advertisement