iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

CSS Float

float pulls an element out of normal flow and pins it to the left or right of its container, letting text wrap around it. It's been mostly replaced by Flexbox and Grid for layout — but it's still the right tool for one job: text wrap.

Text wrapping

img float: left Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent commodo cursus magna, vel scelerisque nisl consectetur. Sed posuere consectetur est at lobortis. Text after the floated element wraps under it.
Fig 1. A left-floated image with text wrapping around it.

Values and the clearfix problem

PropertyValueEffect
floatleft, right, noneWhere the element parks.
clearleft, right, both, nonePushes this element below the floats above it.

Because a floated child doesn't contribute to its parent's height, the parent can collapse. The modern fix is one line:

CSS
.parent { display: flow-root; }   /* contains the floats — no clearfix hack needed */
Tip: Use float only for text wrapping these days. For grids, sidebars, navbars — reach for Flexbox or Grid instead.

Example

Example
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: Verdana, sans-serif; }
.box { background: #04AA6D; color: #fff; padding: 20px; border-radius: 6px; }
</style>
</head>
<body>

<h1>CSS Float</h1>
<div class="box">Edit the CSS on the left, then click Run &raquo;</div>

</body>
</html>
Try it Yourself »

Exercise

Float this thumbnail to the left so text wraps around it.

img.thumb { : left; margin-right: 12px; }

Test yourself

Q1. What is the main remaining use case for `float`?
Q2. A parent that only contains floated children may collapse to zero height. The cleanest modern fix is…
Q3. Which property pushes an element below the floats above it?

Discussion

Loading…