The CSS clear Property
The clear property sets what should happen with the element next to a floating element. It stops elements from wrapping around or sitting beside the floated content.
It can take these values: none, left, right, both, and inherit.
Example
clear: left pushes the second div down, below the floated first div.
Prompt
An HTML page showing the clear property.
In an internal
<style> block, float div1 to the left (as a colored box) and give div2 clear: left with a border, so div2 is pushed below the floated div1 instead of beside it. Add both divs.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.div1 {
float: left;
width: 100px;
height: 70px;
background-color: #4CAF50;
}
.div2 {
clear: left;
border: 2px solid red;
}
</style>
</head>
<body>
<div class="div1">div1</div>
<div class="div2">div2 - Because clear: left is set, this div is pushed below the floated div1.</div>
</body>
</html>
The CSS Clearfix Hack
If a floated element is taller than its container, it overflows outside the container. The clearfix hack fixes this.
The clearfix hack uses the ::after pseudo-element to make the parent container properly enclose its floated children.
Example
The clearfix class makes the container wrap around its tall floated child.
Prompt
An HTML page that uses the clearfix hack so a container encloses its tall floated child.
In an internal
<style> block, give a container a border, float a tall box inside it, and add a .clearfix::after rule with content "", clear both, and display table. Apply the clearfix class to the container so it properly wraps the floated child.
Output: complete HTML page
index.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.box {
border: 3px solid #4CAF50;
}
.box img {
float: right;
}
.imgbox {
float: right;
width: 100px;
height: 170px;
background-color: #4CAF50;
}
.clearfix::after {
content: "";
clear: both;
display: table;
}
</style>
</head>
<body>
<h3>With clearfix</h3>
<div class="box clearfix">
<div class="imgbox"></div>
Some text. The clearfix hack makes the green border enclose the tall floated box.
</div>
</body>
</html>
CSS Properties
A summary of the properties here:
clear— sets what happens with the element next to a floated element.float— sets whether and how an element floats.