Search code examples
htmlcsspseudo-class

Clearing elements with div:after


While looking for a solution to this question, I attempted to add a clearing element with the :after pseudo-class. It did what I want, but not for the reason I expected - after narrowing things down I found out that defining the following clears the elements:

.right_field > div:after
{
    content: "style=\"foo\"";
}

What I would expect it to do is append the text style="foo" to the end of the div elements inside the .right_field, but instead it adds nothing visual and clears the elements so that they wrap around their floating children.

See the following fiddle for a demonstration. Try removing the foo from inside the content property and see how it no longer clears the element and instead just appends the text to each of them. http://jsfiddle.net/dNJxd/5/

Why does this happen, and is this a feature that can be counted on? I tested it on Chrome, Firefox and IE7-9 and they all worked the same way.


Solution

  • Your example does append the text style="foo" after the div element. The only browser that wouldn't do this (from your list of tested browsers) is IE7 because it does not support the ::after pseudo class.

    Maybe you need to stretch out your JSFiddle result window a little further.

    Also, this does not clear the float - it just gives the parent div some height since the appended text is not floated. The border collapse will still occur when the content of the div has a larger height than the appended text.