Bootstrap float utility is very helpful in positioning the components properly on the web-page.
But there are is an issue in this approach that needs to be addressed. Check out the code below to know about the same:
Check this code in you browser and you will find a problem with the floats.
Sample text in the div. This is the second line. The line 3 comes next. And then comes the final line h
If you load this code on a browser, you can observer following points:
- A <div> is created with a green border and some text content in it
- The <img> added to this <div> is made to float to the right of the div
- The image is overflowing from the <div> component
The third point is the float issue we were talking about.
When you make any element to float, it might flow around its containing element.
This is bad for the styling on the webpage as the components not look very neat.
To fix this problem we have special hack in Bootstrap called the ‘clearfix’ hack.
Here we will understand what the ‘Clearfix’ hack is and how it can help us to solve the problem we discussed before.
Clearfix Hack
Basically clearfix, clears the overflowing float component.
You can add the clearfix to the containing element (like the <div> in this case) and will contain the floating element withing itself so it doesn’t overflow.
The code below explains how you can use clearfix in CSS. Based on this knowledge, we will understand how we can use clearfix in Bootstrap.
Check this code in your browser and see how clearfix solves the overflowing float issue
Add a clearfix class with overflow: auto; to the containing element, to fix this problem:
Sample text in the div. This is the second line. The line 3 comes next. And then comes the final line
Now that, we have understood the basic working of a clearfix, let’s move to Bootstrap.
Bootstrap Clearfix Utilities
So, we know that Clearfix quickly and easily clears the floated content within a container.
The basic classe used for this is the .clearfix. This is used with the parent element.
...
You can also use clearfix with Mixins
// Mixin itself
@mixinclearfix() {
&::after {
display: block;
content: "";
clear: both;
}
}
// Usage as a mixin
.element {
@include clearfix;
}
Check the code snippet below to understand how clearfix can be used in Bootstrap in a typical webpage