When utilizing the float property, if we aim to position the next element below (not to the right or left), we employ the clear property.
Clear determines the behavior of an element positioned adjacent to a floating element.
The clear property options are:
For proper float clearing, align the clear property with the float: If an element is floated to the left, clear to the left. This ensures the floated element retains its position, while the cleared element appears below it on the webpage.
Example
In this example, the float is cleared to the left. Consequently, the <div2> element is positioned beneath the left-floated <div1> element.
div1 { float: left; } div2 { clear: left; } |
When a floated element exceeds the height of its container, it extends beyond the container’s boundaries. To address this issue, we can apply a clearfix hack.
Example
.clearfix { overflow: auto; } |
The overflow: auto clearfix is effective as long as you can manage margins and padding to avoid unintended scrollbars. However, the newer, modern clearfix hack is considered safer and is commonly employed in most web pages. The following code snippet is widely used for this purpose:
Example
.clearfix::after { content: “”; clear: both; display: table; } |
You’ll delve deeper into the ::after pseudo-element in a subsequent chapter. |