Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion as to how clearfix actually works

Tags:

css

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?

like image 712
Cameron Avatar asked Sep 09 '11 12:09

Cameron


People also ask

How does Clearfix hack work?

The clearfix, for those unaware, is a CSS hack that solves a persistent bug that occurs when two floated elements are stacked next to each other. When elements are aligned this way, the parent container ends up with a height of 0, and it can easily wreak havoc on a layout.

How do you use the Clearfix technique?

A clearfix is a way for an element to automatically clear or fix its elements so that it does not need to add additional markup. It is generally used in float layouts where elements are floated to be stacked horizontally.

When should I use Clearfix?

The clearfix property is generally used in float layouts where elements are floated to be stacked horizontally. The CSS float property states how an element should float; i.e., it specifies the position where an element should be placed. The clearfix property allows a container to wrap its floated children.

What is wrapper Clearfix?

You can create quickly and easily clear floated content by adding a clearfix utility class ( . clearfix) to the parent element. It can also be used as a mixin. Detailed documentation and more examples you can find in our Bootstrap Clearfix Docs.


1 Answers

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

like image 144
duri Avatar answered Oct 02 '22 01:10

duri