Different Clearing Techniques
Explore various CSS clearing techniques to handle float elements effectively, including the use of empty divs, overflow properties, clearfix pseudo-elements, and the modern flow-root display property. This lesson helps you understand how to maintain proper layout and container height in HTML designs with floated elements.
Problem statement
You will need to add the background color to the outer div so that it covers both the main-content and sidebar areas. Set the background color of the outer div to yellow. The main-content div takes 70% of the page width and floats on the left side. The sidebar div takes 25% of the page width and floats on the right side. Add a 5px solid coral border to both divs.
Your output will look like this:
Solution review with different clearing techniques
Using empty div with clear: both
One way to clear the last float element is to insert an empty div after the last child div with clear: both. What this does is clears the left as well as the right of the empty div and helps the parent element calculate its height correctly. It is also possible to use other empty elements such as <br>, with the clear: both property. However, divs are preferred because there generally isn’t any browser-default associated with them. We added an empty div with the clear: both style at line 31 of the HTML page.
Using the overflow method
If we set overflow to hidden or auto on the parent element (outer), the parent will expand to contain the floats, effectively clearing it for succeeding elements. This method is beneficial as we don’t need any extra space for div to apply the property. This method is not explicitly used for clearing floats as it sometimes disturbs the flow of scrollbars or hides useful content. Look at line 3 of the CSS page.
Using the famous clearfix technique
In order to achieve the required output, we can add an additional class to the parent outer div. The :after pseudo selector is used with the .clearfix class to clear floats. We can apply the following CSS:
.clearfix:after {
content: "";
display: block;
height: 0;
clear: both;
}
With content: "", there is no content added after the parent element. With height: 0, this will not take any extra height on the page. The clear: both clears the float from both the main-content and sidebar areas.
Using display: flow-root on the parent element
The modern way of solving this problem is to use the value flow-root of the display property on the parent element. The parent element generates a block container box and lays out its contents using the flow layout. It always establishes a new block formatting context for its contents.