What is Clearfix in CSS
Float can be used to lay out elements. Clearfix is a method used to fix the zero-height container issue caused by floated elements.
Here is an example of arranging items vertically using float (live preview):
|
|
|
|
Three items are properly arranged, but the outer element is at the right side of item3.
|
|
The outer element should be under all items.
|
|
Since three items are floated, they are removed from the normal flow. As a result, .container
contains nothing, so its height is 0. That’s why the outer element isn’t under three items. Here is the classic method for fixing the height:
|
|
Breakdown:
.clearfix::after
creates an element and append it to.clearfix
(.container
)content: '';
means the element is empty.display: block;
means the element is a block element.clear: both;
puts the element under left floated elements and right floated elements.- Since
.clearfix
(.container
) has an element now, its height becomes normal. - You can see the element by applying
content: 'hi'
.
The classic method is obsolete and difficult to understand. Here is the modern and simpler method:
|
|
display: flow-root
makes the container establish a block formatting context, which contains internal floated elements. For more details on block formatting context, see What is Block Formatting Context (BFC) in CSS.
Note that float layout is hacky and obsolete. Use flexbox or grid instead.
comments powered by Disqus