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 1
Div 2
Div 3
.div {
width: 80px;
height: 80px;
background: red;
margin: 4px;
}
.div_1, .div_2 {
float: left;
}
.div_3 {
clear: left;
}
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.
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
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.
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
img {
float: left;
padding-right: 8px;
}
.clearfix::after {
content: ""; /* no content */
clear: both;
display: table;
}
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.
Why 1SMARTchicken?
See More →
Thanks for your support!
CSS Books
All are affiliate links. Thank you for your support!
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
Feedback
If you see an error on the page or the code itself is incorrect or incomplete, or just plain wrong, please let us know. We’re always learning. NOTE: we do not sell your information and will not send you spam emails.