CSS float / clear
- type
- properties
- applies to
- block elements
- inherits
- no
- common values
- left | right | none; clear: both
Where it goes
On an image or figure inside running text, with a margin on the side the text wraps against. If a parent only contains floats it collapses to zero height. display: flow-root on the parent makes it contain them.
Example
.figure-left {
float: left;
margin: 0 16px 8px 0;
}
.article { display: flow-root; } /* contains the float */
.footer { clear: both; }Common mistakes
- Building a page layout with floats today. Columns, nav bars and card grids are flexbox or grid jobs. Floats need hacks and break the moment content heights differ.
- Floating a box and wondering why the parent's background vanished. Floated children leave the flow, so the parent has no height. Add display: flow-root to the parent.
- Floating the only child and then trying to center it. A float cannot be centered. Use flex, or margin: auto on a block.