Enjoy 20% off all plans by following us on social media. Check out other promotions!
Quiz Questions

Describe `float`s and how they work.

Topics
CSS
Edit on GitHub

Float is a CSS positioning property. Floated elements remain a part of the flow of the page, and will affect the positioning of other elements (e.g. text will flow around floated elements), unlike position: absolute elements, which are removed from the flow of the page.

The CSS clear property can be used to be positioned below left/right/both floated elements.

If a parent element contains nothing but floated elements, its height will be collapsed to nothing. It can be fixed by clearing the float after the floated elements in the container but before the close of the container.

Clearfix hack

The .clearfix hack uses a clever CSS pseudo-element (::after) to clear floats. Rather than setting the overflow on the parent, you apply an additional class clearfix to it. Then apply this CSS:

.clearfix::after {
content: ' ';
visibility: hidden;
display: block;
height: 0;
clear: both;
}

Alternatively, give overflow: auto or overflow: hidden property to the parent element which will establish a new block formatting context inside the children and it will expand to contain its children.

Trivia

In the good old days, CSS frameworks such as Bootstrap 2 used the float property to implement its grid system. However with CSS Flexbox and Grid these days, there is no longer much need to use the float property.

References

Edit on GitHub