Float & Clear
Float was historically used for layouts but is now primarily used for wrapping text around images. Clear prevents elements from appearing next to floated elements. Modern layouts use flexbox and grid instead.
Float Basics
CSS
/* Float left */
img {
float: left;
/* Image floats left, text wraps around */
}
/* Float right */
img {
float: right;
/* Image floats right, text wraps around */
}
/* No float (default) */
img {
float: none;
}
/* Multiple floated elements */
.image-left {
float: left;
margin-right: 20px;
}
.image-right {
float: right;
margin-left: 20px;
}Clear
CSS
/* Clear prevents elements next to floated elements */
.clear-left {
clear: left;
/* No floated elements to the left */
}
.clear-right {
clear: right;
/* No floated elements to the right */
}
.clear-both {
clear: both;
/* No floated elements on either side */
}
/* Clearfix technique (legacy) */
.clearfix::after {
content: '';
display: table;
clear: both;
}Modern Alternatives
CSS
/* Instead of float, use flexbox */
.container {
display: flex;
gap: 20px;
}
.image {
flex-shrink: 0;
}
.text {
flex: 1;
}
/* Or use grid */
.container {
display: grid;
grid-template-columns: auto 1fr;
gap: 20px;
}
.image {
/* Auto width */
}
.text {
/* Fills remaining space */
}Warning
Float is legacy for layouts. Modern CSS uses flexbox and grid instead. Only use float for wrapping text around images.
Note
Float was used historically for layouts but is now mainly for text wrapping. Clear prevents elements from appearing next to floats. Use flexbox or grid for modern layouts instead.
Next
Content-box vs border-box: [content-box vs border-box](/css/content-box-vs-border-box).