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?
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.
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.
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.
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.
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With