DEV Community

Abdullah Al Numan
Abdullah Al Numan

Posted on

Describe floats in CSS and how they work.

In CSS, floats are created by setting the float property of an element to a value other than none.

div {
  float: left;
}
Enter fullscreen mode Exit fullscreen mode

Floating an image with text wrapped around it, is a common implementation of the float property. An element can be floated right or left, with assignable values of right, left, inline-start and inline-end.

Floating an element creates a Block Formatting Context on the element, takes the element out of the normal flow of the document, and wraps around itself line boxes that come after the element in the DOM tree.

Items floated to the left, move to the left edge of its container and those floated to the right move to the right edge.

Multiple items floated to the same edge follow the order in which they appear in the DOM tree, with the first one moved to the edge, then the next one beside it, and so on -- ending up with the last one farthest from the edge. If there is no space to accommodate all floated items, they move to the next line.

In almost all cases, using a float also involves clearing it from one item that come after itself, because line boxes (e.g. text nodes) wrap around floated items. Clearing a float from an element results in moving the element below the float.

Floats, along with several clearing techniques, were used to create multi-column layouts, but flex and grid items are nowadays used for this purpose.


References

  1. Floats
  2. float
  3. clear

Top comments (3)

Collapse
 
nombrekeff profile image
Keff

I expected the post to talk about the other kind of floats xD

Collapse
 
anewman15 profile image
Abdullah Al Numan • Edited

This is intended to provide a short answer in an interview set up, so keeping it that way. inline-start and inline-end eventually compute to either right or left in a given horizontal writing mode

Collapse
 
nombrekeff profile image
Keff

I though it was about floating point numbers, I forgot css called this float as well xD