The clear property in CSS is used to control the behavior of floating elements. It specifies whether an element should be moved down to avoid floating elements on the left, right, or both sides. This property is commonly used to clear floats and ensure that elements are properly positioned within their containers.
The clear property can take the following values:
Here are some examples demonstrating how to use the clear property:
.clear-left {
clear: left;
background-color: lightcoral;
padding: 10px;
}
.float-left {
float: left;
width: 150px;
height: 150px;
margin: 10px;
background-color: lightblue;
}
In this example, the element with clear: left; will move down to avoid any left-floating elements.
.clear-right {
clear: right;
background-color: lightcoral;
padding: 10px;
}
.float-right {
float: right;
width: 150px;
height: 150px;
margin: 10px;
background-color: lightgreen;
}
In this example, the element with clear: right; will move down to avoid any right-floating elements.
.clear-both {
clear: both;
background-color: lightcoral;
padding: 10px;
}
.float-left {
float: left;
width: 150px;
height: 150px;
margin: 10px;
background-color: lightblue;
}
.float-right {
float: right;
width: 150px;
height: 150px;
margin: 10px;
background-color: lightgreen;
}
In this example, the element with clear: both; will move down to avoid any floating elements on either side.
Here are some practical tips and important notes to keep in mind when using the clear property:
.container {
background-color: lightgrey;
}
.clearfix::after {
content: "";
display: table;
clear: both;
}
.box {
float: left;
width: 100px;
height: 100px;
margin: 10px;
background-color: red;
}
The clear property in CSS is a powerful tool for managing the behavior of floating elements. By understanding and using the clear property, you can ensure that your layouts are stable and elements are properly positioned. Remember to use the clearfix hack for containers and consider layout stability in responsive designs.