Home >Web Front-end >CSS Tutorial >What's the Purpose of 'clear:both' in CSS?
Understanding the Role of "clear:both" in CSS
When a web page has elements that are floated left or right, it can cause subsequent elements to flow around them. To prevent this, CSS provides the "clear" property, which can be set to a specific side (left, right) or to "both".
What is the Use of "clear:both"?
"clear:both" instructs the element to drop below any preceding elements that have been floated left and right. This allows it to start on a new line, clearing any margins or padding that might otherwise wrap around the floated elements.
How Does "clear:both" Work?
In a normal document flow, elements are stacked vertically, with content flowing around them. However, when an element is floated, it shifts either left or right, allowing other content to flow below it. "clear:both" tells the current element to start below any previously floated elements on both sides.
Example Usage
Consider the following HTML code:
<div>
In this example, the "Left float" div is floated to the left, causing the "This is a paragraph" text to wrap around it. The "Clear both" div is then used to clear both the left and right sides, allowing the "This is a new paragraph" text to appear below it in a new line.
Conclusion
By setting "clear:both" on an element, you can ensure that it starts on a new line below any previously floated elements, ensuring a consistent and controlled layout.
The above is the detailed content of What's the Purpose of 'clear:both' in CSS?. For more information, please follow other related articles on the PHP Chinese website!