The CSS clear
property is used to control the behavior of an element when it comes into contact with floated elements. This property specifies on which sides (left, right, both) an element is not allowed to float next to floated elements.
Syntax
clear: none | left | right | both | inline-start | inline-end | inherit;
Values
none
: Default value. Allows elements to float on both sides.left
: No floating elements allowed on the left side of the element.right
: No floating elements allowed on the right side of the element.both
: No floating elements allowed on either the left or right side.inline-start
: No floating elements allowed on the inline start side.inline-end
: No floating elements allowed on the inline end side.inherit
: Inherits the value from its parent element.
Example
Here is a simple example demonstrating how the clear
property works:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CSS Clear Example</title> <style> .container { width: 600px; margin: 20px auto; border: 1px solid #ccc; padding: 10px; } .box { width: 200px; height: 100px; float: left; margin: 10px; background-color: lightblue; text-align: center; line-height: 100px; font-size: 1.2em; } .clear-both { clear: both; background-color: lightgreen; text-align: center; padding: 10px; font-size: 1.2em; } </style> </head> <body> <div class="container"> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="clear-both">Cleared Both</div> <div class="box">Box 3</div> <div class="box">Box 4</div> </div> </body> </html>
Explanation
- HTML Structure:
.container
: A parentdiv
that contains floated boxes and aclear
element..box
: These are floated elements (float: left;
), meaning they align next to each other horizontally if there’s enough space..clear-both
: This element usesclear: both;
to prevent it from floating next to the.box
elements, ensuring it appears below them.
- CSS Styling:
float: left;
: Floats.box
elements to the left.clear: both;
: Ensures that.clear-both
is below all floated elements on both sides.
Practical Use
- The
clear
property is commonly used when you need to ensure that an element appears below floated elements. - It’s often used with layout elements like footers, to make sure they don’t get positioned next to floated sidebars or content areas.
This example provides a foundational understanding of the clear
property, demonstrating its use to manage layout and positioning in the presence of floated elements.