Clearfix are used to avoid elements collapsing into each other and is usually done by just adding an extra div with clear:both rule.
What’re some other ways of applying clearfix? also, is it a good practice to use clearfix?
I really don't like to use extra divs, and classes just for something like that. If something can be done with just 2 type of elements, parent and child why using another 100 just to fix old style css. Depending on the case I use just overflow: hidden on parent and display block on children for easy stuff or just use Flexbox. I really don't like and haven't use clear:both nor float: left or right; or at least not very often cause I believe those are old school fixes that does not have a constant behaviour.
Hey @sharon_c, yes you are right, clearfix is used to keep the floated children elements within their parent element. The absence of a clearfix declartion on the parent element causes it to loose hold of the children element within it.
One of the ways to implement clear fix is exactly what you did mention: adding another block element (like: <div>) with a clearfix property applied to it. Like so :
div {
clear: both;
}
The other approach is better and cleaner than first. Unlike the first which requires an addition of an html markup (<div>) all for the purpose of keeping floated child elements in place their parent, this approach requires no extra html markup to convolute your beautifully crafted, probably component based html markup. This should do the same trick as the first approach did:
div:after {
content: "";
display: block;
clear:both;
}
Note that the <div> in the above code snippet is the <div>housing the floated child elements.
Another snippet showing the same implement of clearfix with the second approach:
Assuming we have an html markup like so: <div class="container"> <div class="item item-float">Item 1</div> <div class="item item-float">Item 2</div> <div class="item item-float">Item 3</div> </div>
Now to keep the <div> elements with class of .item within their parent container with class of .container, we add this piece of css. .container { width: 80%; margin: auto auto; border: 1px solid red; }
/** This is what does the clearfix magic */
.container:after {
content: "";
clear: both;
display: block;
}
.item {
width: 45%;
height: 100px;
border: 1px solid blue;
}
.item-float {
float: left;
}
Hope this helps.
Yes, It works and is that simple: If you e.g. come to the end of a bootstrap div/code block styled with class panel, or you used a class float for layout; by using clearfix, your next div (after the styled div) appears below the first instead of next to it. It can be really handy to get the layout you need.
Emil Moe
Senior Data Engineer
Wrap it in a container and give it
overflow: hidden;