CSS中连续设置float属性的div是否必须使用clear属性?
clear for Two Consecutive Floated <div>s? Great question—this is a super common point of confusion when working with CSS floats, so let’s break it down in plain terms.
First, a quick refresher on how floats behave: when you set an element to float: left or float: right, it pulls out of the normal document flow and shifts to the specified edge of its container, stopping only when it hits the container’s boundary or another floated element.
The Short Answer: No, You Don’t Always Need clear
Whether you need the clear property depends entirely on what layout you’re trying to build:
1. If you want the two divs to sit side-by-side
If both divs use the same float direction (e.g., both float: left) or opposite directions (one left, one right), they’ll naturally position themselves next to each other—no clear required—as long as their combined width (including margins, padding, and borders) doesn’t exceed the container’s width.
Here’s a quick example:
.container { width: 100%; padding: 10px; box-sizing: border-box; } .card-left { float: left; width: 45%; height: 120px; margin-right: 5%; background: #f0f0f0; } .card-right { float: right; width: 45%; height: 120px; background: #e0e0e0; }
In this case, the two divs will sit neatly side-by-side without overlapping, and you won’t need to add clear anywhere.
2. When you DO need clear
You only need clear when you want an element to ignore the floated elements above it and snap back to the normal document flow. For example:
- If you want the second floated div to sit directly below the first one (not side-by-side), add
clear: left(orclear: both) to the second div. - If your parent container is collapsing in height (because it only contains floated elements), you’ll need a clearfix hack (which uses
clearunder the hood) to force the parent to recognize its floated children’s height.
Why You Might Have Seen Overlapping
Your initial issue with overlapping probably happened because the combined width of your floated divs exceeded the container’s width, causing the second div to wrap underneath—but if the first div was taller, the second might have looked like it was overlapping. In that case, adjusting widths/margins to fit the container is a better fix than adding clear (unless you intentionally want them stacked).
内容的提问来源于stack exchange,提问作者Rezwana

