Categories
CSS clear
is a property used to control the behavior of elements concerning floated elements within the same containing element. When an element is floated, it is taken out of the normal document flow, which can affect the layout of subsequent elements. The clear
property allows you to specify whether an element should be moved below any floated elements that precede it or not.
There are four possible values for the clear
property:
-
clear: left;
: The element will not be allowed to float on the left side of any preceding floated elements. -
clear: right;
: The element will not be allowed to float on the right side of any preceding floated elements. -
clear: both;
: The element will not be allowed to float on either the left or right side of any preceding floated elements. It will be moved below any floated elements. -
clear: none;
(default): The element will be allowed to float on either side of any preceding floated elements.
Here are some examples to illustrate the usage of the clear
property:
1. Clearing floats to the left:
HTML:
<div class="container">
<div class="box float-left">Float Left</div>
<div class="box clear-left">Clear Left</div>
</div>
CSS:
.container {
width: 300px;
}
.box {
width: 100px;
height: 100px;
margin: 5px;
}
.float-left {
float: left;
}
.clear-left {
clear: left;
}
2. Clearing floats to the right:
HTML:
<div class="container">
<div class="box float-right">Float Right</div>
<div class="box clear-right">Clear Right</div>
</div>
CSS:
.container {
width: 300px;
}
.box {
width: 100px;
height: 100px;
margin: 5px;
}
.float-right {
float: right;
}
.clear-right {
clear: right;
}
3. Clearing floats on both sides:
HTML:
<div class="container">
<div class="box float-left">Float Left</div>
<div class="box float-right">Float Right</div>
<div class="box clear-both">Clear Both</div>
</div>
CSS:
.container {
width: 300px;
}
.box {
width: 100px;
height: 100px;
margin: 5px;
}
.float-left {
float: left;
}
.float-right {
float: right;
}
.clear-both {
clear: both;
}
4. Using clear
within a multi-column layout:
HTML:
<div class="column">
<p>Column 1</p>
</div>
<div class="column">
<p>Column 2</p>
</div>
<div class="clearfix"></div>
CSS:
.column {
width: 150px;
float: left;
}
.clearfix {
clear: both;
}
In this example, we use the clearfix class to clear the floats after the two columns to ensure that subsequent content is not affected by the floated elements.