What is the use of style="clear:both"?
The style="clear:both"
attribute forces an element to start below any floated elements both on the left and right, thus preventing any unwanted wrapping. This technique is prevalently employed to preserve the structure of a layout after floating elements such as sidebars or images.
Here's a quick demonstration:
With clear
we can precisely manage how elements are stacked in the layout flow after floated ones. It's not just about clear:both
; clear:left
and clear:right
are also useful for keeping your layout in control.
Dissecting clear
The mighty clear:both
At a basic level, clear:both
tells the browser to "Hold your horses! 🐴" and asks it to place an element below any previous floated elements. It comes into play particularly in multi-column layouts where you wish the main content to not be affected by floating elements like widgets or ads.
Side-specific clearing
For circumstances where you only need to clear floating elements from a specific side, clear:left
and clear:right
come to the rescue. This specific control is useful when we fancy a specific flow of text around images or deal with sidebar-footer alignments.
Potential mishaps and solutions
- Nested paradox: Floats within floats can cause a layout chaos. A quick
clear:both
can act as an eject button, saving your layout. - Parental woes: In case all children are floated, the parent may collapse.
clear:both
can effectively clear the way for the layout to remain in control. - Inline hurdles:
clear
is designed for block-level elements, to clear on inline elements, adjust their display value toblock
orinline-block
.
Tips and tricks
Enter the clearfix
The clearfix hack acts as a guardian angel by containing floats without additional markup. It encourages semantic coding with the help of pseudo-elements and avoids turning your page into a meaningless div city.
Semantic HTML for the win
While clear
is a lifesaver when it comes to fixing the layout, overuse can lead to unyielding, messy code that ends up being a div soup. As Spider Man would say, "with great power, comes great responsibility". Maintain a balance between using clear
and keeping your HTML code semantic and accessible.
Floatutorial and beyond
Consider Floatutorial as your professor, providing in-depth tutorials for mastering floats and clear. Investing time equals cleaner and more efficient code.
Was this article helpful?