CSS: Floating elements & resizing container (ClearFix)

This is a problem I’ve ran into many times especially when I first started using CSS and divs to build websites, you may have noticed (or not) that if you have a container DIV with some child DIVs which are using the float: attribute the container doesn’t resize to fit the child DIVs, if you where to remove the float: attribute from the child DIVs the container will adjust to the size of the containers again.

Example 1

This is child 1
This is child 2

HTML Code

This is child 1
This is child 2

CSS Code

.container {
	border: thick solid #000;
	width: 200px;
}
.child1 {
	width: 100px;
	background-color: #0C0;
}
.child2 {
	width: 100px;
	background-color: #C30;
}

From this example above you can see what a container DIV looks like when the child DIVs do not contain the float: attribute, the container DIV resizes and adjusts depending on the size of the child DIVs, but without the float attribute are two child DIVs do not fit side by side.

Example 2

This is child 1
This is child 2

HTML Code

This is child 1
This is child 2

CSS Code

.container {
	border: thick solid #000;
	width: 200px;
}
.child1 {
	width: 100px;
	background-color: #0C0;
	float: left;
}
.child2 {
	width: 100px;
	background-color: #C30;
	float: left;
}

Now we are using the exact same code above the only difference is the float: attribute is now being used which allows the two child DIVs to sit next to each other, but now are container has stopped resizing and shows as if there is no data present. There is a simple and effective fix using CSS which will allow the container to resize exactly how it does in example 1 but still allow the two child DIVs to use the float: attribute, below is the CSS code which fixes this problem.

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

Using this CSS code is very simple, all you have to do is simply rename .clearfix (making sure to leave :after as this will make the CSS apply after loading all the elements, if it is applied before it will load incorrectly and may not work) with the name of the class used for your container DIV (if you have used id instead you need to replace the . with a #), this CSS code can be used in a variety of ways but this is the simplest, I have provided an example below demonstrating it working using the code from example 2.

Example 2 with ClearFix

This is child 1
This is child 2

HTML Code

This is child 1
This is child 2

CSS Code

.container {
	border: thick solid #000;
	width: 200px;
}
.container:after
{
	content: ".";
	display:block;
	height:0;
	clear:both;
	visibility:hidden;
}
.child1 {
	width: 100px;
	background-color: #0C0;
	float: left;
}
.child2 {
	width: 100px;
	background-color: #C30;
	float: left;
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.