CSS Introduction | CSS Position Properties | Float
CSS float Properties
| Property | Description |
|---|---|
| float | Sets an HTML element so it naturally flows with surrounding elements. |
| clear | Sets elements that appear after a floated element so they are no longer affected by the float property. |
| overflow | Sets how content is handled when it is larger than the container element surrounding it. |
| overflow-x | Sets how content is handled when it exceeds the element’s horizontal box. |
| overflow-y | Sets how content is handled when it exceeds the element’s vertical box. |
float Property
The float property makes the corresponding HTML element naturally flow with surrounding elements.
This property was originally created for that purpose, but today it is often used when creating web page layouts.
The following example displays an image and text together.
<style>
img { float: left; margin-right: 20px; }
</style>
clear Property
The clear property controls the behavior of elements that appear after the float property has been applied.
When the float property is applied to a container element, it becomes very difficult to set the exact position of all elements that appear afterward.
<style>
.left { background-color: #FF8C00; width: 150px; height: 50px; float: left; }
.right { background-color: #9932CC; width: 150px; height: 50px; float: right; }
</style>
Therefore, after all elements that should use the float property have appeared, use the clear property so that later elements are no longer affected by the float property.
<style>
.left { background-color: #FF8C00; width: 150px; height: 50px; float: left; }
.right { background-color: #9932CC; width: 150px; height: 50px; float: right; }
p { clear: both; }
</style>
overflow Property
If an HTML element with the float property applied is larger than the container element that wraps it, part of the element overflows outside.
At this time, if the overflow property value is set to auto, the container element automatically becomes large enough to wrap the internal element.
<style>
div { border: 3px solid #73AD21; padding: 5px;}
img { float: left; }
.good { overflow: auto; }
</style>
Layout Using the float Property
Many current web page layouts are created using the float property.
The following example shows a layout created using the float property.
<style>
div.page { border: 3px solid #CD5C5C; overflow: auto; }
h2 { text-align: center; }
header{ border: 3px solid #FFD700; }
nav { border: 3px solid #FF1493; width: 150px; float: left; }
section { border: 3px solid #00BFFF; margin-left: 156px; }
footer{ border: 3px solid #00FA9A; }
</style>