InterviewSolution
| 1. |
Why do we need to use clear property along with floats in CSS? |
|
Answer» The clear property ALONG with floats is used for specifying which SIDE of floating elements is not supposed to float. An element having clear property ensures that the element does not move up ADJACENT to the float. But the element will be moved down past the float. Let us understand this with the help of an example. We know that the floated objects do not add to the height of the objects where they reside. Consider we have a div element with class “floated_div” within another div element with id “main_div”. <html> <head> <style> #main_div { width: 400px; margin: 10px auto; border: 4px solid #cccccc; PADDING: 5px; } .floated_div { float: LEFT; width: 50px; height: 50px; border: 2px solid #990000; margin: 10px; } </style> </head> <body> <div id="main_div"> <p>Clear Float Demo</p> <div class="floated_div"></div> <div class="floated_div"></div> <div class="floated_div"></div> <div class="floated_div"></div> <div class="floated_div"></div> </div> </body></html>The result of this code would be as shown below. We see that the squares that are expected to be within dev are not within the main parent div. How do we fix this? We can do it just by adding <div style="clear:both"></div> line at the end of the last floated element so that the floated elements are fit in properly within the main div container. <html> <head> <style> #main_div { width: 400px; margin: 10px auto; border: 4px solid #cccccc; padding: 5px; } .floated_div { float: left; width: 50px; height: 50px; border: 2px solid #990000; margin: 10px; } </style> </head> <body> <div id="main_div"> <p>Clear Float Demo</p> <div class="floated_div"></div> <div class="floated_div"></div> <div class="floated_div"></div> <div class="floated_div"></div> <div class="floated_div"></div> <div style="clear:both"></div> <!-- Adding this fixed the issue --> </div> </body></html>The result of this will be: |
|