When working with floating elements there is one problem web developers usually face. Since float elements are removed from the normal flow of the page, this causes some other side effects that may be seen as undesireable.
Lets begin with this HTML structure:
1
2
3
4
<ul>
<li>One</li>
<li>Two</li>
</ul>
If we wanted to make a menu out of the UL we could make the LIs floating elements like this:
1
2
3
4
5
6
7
8
9
10
11
ul {
list-style: none;
padding: 0;
border: 1px solid #f00;
}
li {
display: block;
float: left;
margin-right: 10px;
}
And we would end up with something like this:
- One
- Two
We can see that the border of the container UL does not wrap the li elements, which is not what we intent in most cases. To stop get the behavior we expect we could add a clear element to our list:
1
2
3
4
5
<ul>
<li>One</li>
<li>Two</li>
<li class='clear'></li>
</ul>
And make it clear with this css:
1
2
3
.clear {
clear: both;
}
We would end up with something like this:
- One
- Two
That works ok, but adding and element to the HTML for styling purposes doesn’t seem right, so a few people have come up with what is commonly referred to as clearfix. One of the most modern versions is attributed to Nicolas Gallagher (http://nicolasgallagher.com/micro-clearfix-hack/) and it goes like this:
First we remove the extra markup we added:
1
2
3
4
<ul>
<li>One</li>
<li>Two</li>
</ul>
Then we use this css:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
ul {
list-style: none;
padding: 0;
border: 1px solid #f00;
}
ul:before,
ul:after{
content: "";
display: table;
}
ul:after{
clear: both;
}
ul {
zoom: 1;
}
li {
display: block;
float: left;
margin-right: 10px;
}
And we would end up with this:
- One
- Two
Nicholas explains in his article what each of the rules do, but I will go very fast over them for completeness sake.
zoom: 1; This is only necessary for IE 7 and 6. This activates the internal hasLayout property of IE. This basically tells IE that this element should take care of it’s size and it’s descendants sizes.
:before, :after These CSS pseudo selectors actually insert content in our page. What we are doing is adding one (empty content: “”;) element at the beginning and one element at the end of our UL.
display: table; This attribute prevents a border collapsing bug.
Finally using it all together we get the expected result.
css
programming
]