Describe floats in CSS and how they work.

anewman15

Abdullah Al Numan

Posted on June 23, 2022

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
💖 💪 🙅 🚩
anewman15
Abdullah Al Numan

Posted on June 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related