The float property in CSS shifts an element to the left or right side, allowing surrounding inline content to wrap around it. While originally designed for wrapping text around images, it is widely used for structural layout arrangements.
How Elements Float
A floated item moves horizontally along the current line. It cannot shift vertically. The element will continue moving in the specified direction until it touches the edge of its containing parent or the margin of another adjacent floated element.
Content that follows a floated box flows along its side. However, content positioned before the floated element in the source order remains unaffected. For instance, if a graphic is floated to the right, subsequent text will naturally fill the space on the left.
To apply this behavior, use the float property with a value of left or right.
Impacts of Floating Elements
When an element is floated, its removed from the normal document flow. This means the container no longer calculates its height based on the floated child, which can lead to collapsing containers.
Implementation Techniques
Applying Float to Containers
You can float block-level elements like div to position them side-by-side.
.box {
float: left;
}
Resetting Flow with Clearance
To prevent subsequent elements from wrapping around a floated item, use the clear property. This forces the element to drop below any floats defined in the specified direction.
.footer {
width: 100%;
height: 100px;
background-color: blueviolet;
/* Ensures no floating elements are allowed on either side */
clear: both;
}
Building a Multi-Column Layout
Floats can be used to create a structure with fixed sidebars and a fluid main content area.
<head>
<style>
* {
margin: 0;
padding: 0;
}
html, body {
width: 100%;
height: 100%;
}
.sidebar-left {
background-color: red;
float: left;
width: 200px;
height: 100%;
}
.sidebar-right {
background-color: yellow;
float: right;
width: 200px;
height: 100%;
}
.main-content {
height: 100%;
background-color: blueviolet;
}
</style>
</head>
<body>
<div class="sidebar-left">left</div>
<div class="sidebar-right">right</div>
<div class="main-content">12321312312312321</div>
</body>
Note that in this specific layout example, the .main-content does not have a float property, allowing it to occupy the remaining space, though the order of HTML elements is crucial for the float behavior to apply correctly.