5

When you have a floating element inside a container element you are required to either set the container to overflow auto or add a clear both after the floated element.

This makes sense as you are clearing the floated elements WITHIN the container.

However when using the clearfix CSS trick you are doing the clear after the container and NOT after the floated elements... I'm confused how this is working as you are now clearing the container and not the floats so it should surely still cause the container to have a dodgy height right? Because if I put the clear both AFTER the container with a physical element it would not work so why does it work with the :after ??

Anyone able to explain this? Thanks

Example:

<div style="border:#000 1px solid;padding:10px;">
    <div style="width:100px;height:100px;background:blue;float:left;"></div>
</div>
<div style="clear:both;"></div>

This would not work work but isn't that what the clearfix virtually does?

Cameron
  • 27,963
  • 100
  • 281
  • 483
  • 1
    Oh, you're referring to the `:after` clearfix... – BoltClock Sep 09 '11 at 12:58
  • **Live demo 1:** http://jsfiddle.net/Papmy/ **Live demo 2:** http://jsfiddle.net/Papmy/1/ (there is a difference as you can see) – Šime Vidas Sep 09 '11 at 12:58
  • possible duplicate of [Which method of 'clearfix' is best?](http://stackoverflow.com/questions/211383/which-method-of-clearfix-is-best) – krtek Sep 09 '11 at 13:00
  • @Krtek: This question is asking how a clearfix works, not which one to use. – BoltClock Sep 09 '11 at 13:00
  • @BoltClock the second answer explains the different methods and link to other pages with better explanation. – krtek Sep 09 '11 at 13:03

1 Answers1

9

The CSS :after pseudoelement means "after the element's content, but still inside an element", not "after the element itself". This is why it works.

The mozilla documentation describes it as follows: https://developer.mozilla.org/en-US/docs/Web/CSS/::after

Michael Kargl
  • 662
  • 10
  • 21
duri
  • 14,991
  • 3
  • 44
  • 49
  • there's other way to do a clearfix than using the :after pseudo-element, check http://stackoverflow.com/questions/211383/which-method-of-clearfix-is-best – krtek Sep 09 '11 at 12:59
  • @BoltClock You're absolutely right. Thank you, I've edited my answer. – duri Sep 09 '11 at 12:59
  • 1
    Since `:after` is a child of the element it's applied to, rather than being a sibling, this puts it within the same [block formatting context](http://www.w3.org/TR/CSS2/visuren.html#block-formatting) as the floats inside, allowing clearance to work as defined in the [spec](http://www.w3.org/TR/CSS2/visuren.html#propdef-clear). – BoltClock Sep 09 '11 at 13:10