Overview
When the float property is used on an element, and then we want the next element to fall below that the floated element, and not to its left or right, the clear property is used.
Clearing an Element
In the following we float the first two elements to the left, and then we want the third element to NOT sit to the right of the second element, but to fall below the two floated elements.
<div class="div_1">Div 1</div>
<div class="div_2">Div 2</div>
<div class="div_3">Div 3</div>
.div {
width: 80px;
height: 80px;
background: red;
margin: 4px;
}
.div_1, .div_2 {
float: left;
}
.div_3 {
clear: left;
width: 95%;
}
The following properties are used to set the clear.
Value | Description |
---|---|
none | The element is not pushed below left or right floated elements (default) |
left | The element is pushed below left floated elements |
right | The element is pushed below right floated elements |
both | The element is pushed below both left and right floated elements |
initial | Sets this property to its default value |
inherit | Inherits this property from its parent element |
Clearfix
There is an issue that occurs when a floated element is taller than the containing element. It will overflow outside of its container. We can create a special class called .clearfix to take care of this problem and keep the floated element from overflowing outside the parent container.
The following has a tall image that will overflow the <p> element.
<p>
<img decoding="async" src="very_tall_image.jpg" width="200" height="600" alt="My Image" />
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
img {
float: left;
padding-right: 8px;
}
What we do is add a .clearfix class to the image and then write a special rule that will be applied to all elements with the class .clearfix and keep them from overflowing.
So in the following we have the image floating left, and because we added the .clearfix class to it, it will not overflow the <p> element.
<p>
<img loading="lazy" decoding="async" class="clearfix" src="very_tall_image.jpg" width="200" height="600" alt="My Image" />
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
</p>
img {
float: left;
padding-right: 8px;
}
.clearfix::after {
content: ""; /* no content */
clear: both;
display: table;
}
CSS Notes:
- The “inherit”, “initial” and “unset” keywords can be used with any CSS property to set its value
- In CSS there are many ways to express a color value in a property
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.