9

I use clearfix to clear the float. But the problem is ,there is a different height in <li> and <div>. li.clearfix height is 32px, but div.clearfix height is 18px. when I delete .clearfix:before , they are all the same. But, when tried in bootstrap, it's failed.(I delete the .clearfix:before in bootstrap, but there is still a difference in height.)

<style>
.pull-left{
   float:left;
}
.clearfix {
  *zoom: 1;
}

.clearfix:before,
.clearfix:after {
  display: table;
  line-height: 0;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style> 
<div class="clearfix">
    <div class="pull-left">Hello</div>
</div>
<ul>
    <li class="clearfix"><div class="pull-left">hello</div></li>
</ul>

Demo:http://jsfiddle.net/nevimop/p4HMS/

browsers (chrome safari ie10 , no problem in ff)

enter image description here

add this ul{list-style: none;} the heights same.

Mike Causer
  • 8,196
  • 2
  • 43
  • 63
user3114590
  • 121
  • 1
  • 5

2 Answers2

4

Clearfix is used to force the parent of floated element(s) to receive a height, it does this by using display: table on :before and :after pseudo elements to contain the margins of it's children and then uses clear: both on the :after element to clear it's own float. Together this allows us to apply a clearfix without needing additional markup.

If we force the :before pseudo element not to use display: table and instead use display: inline we can solve your issue of the unnecessary white-space.

li.clearfix:before {
    display: inline;
}

http://jsfiddle.net/72Nmy/

Adam
  • 121
  • 1
  • 2
1

Is there any reason why do you set :after and :before as display:table; instead of display:block;

Something like this: http://jsfiddle.net/N6sG7/3/

.clearfix:before,
.clearfix:after {
  display: table;
  line-height: 0;
  content: "";
  display:block;
  height:0;
}
Slavenko Miljic
  • 3,836
  • 2
  • 23
  • 36