Although elements like <div>
s normally grow to fit their contents, using the float
property can cause a startling problem for CSS newbies: If floated elements have non-floated parent elements, the parent will collapse.
For example:
<div>
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div>
The parent div in this example will not expand to contain its floated children - it will appear to have height: 0
.
How do you solve this problem?
I would like to create an exhaustive list of solutions here. If you're aware of cross-browser compatibility issues, please point them out.
Solution 1
Float the parent.
<div style="float: left;">
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div>
Pros: Semantic code.
Cons: You may not always want the parent floated. Even if you do, do you float the parents' parent, and so on? Must you float every ancestor element?
Solution 2
Give the parent an explicit height.
<div style="height: 300px;">
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div>
Pros: Semantic code.
Cons: Not flexible - if the content changes or the browser is resized, the layout will break.
Solution 3
Append a "spacer" element inside the parent element, like this:
<div>
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
<div class="spacer" style="clear: both;"></div>
</div>
Pros: Straightforward to code.
Cons: Not semantic; the spacer div exists only as a layout hack.
Solution 4
Set parent to overflow: auto
.
<div style="overflow: auto;">
<div style="float: left;">Div 1</div>
<div style="float: left;">Div 2</div>
</div>
Pros: Doesn't require extra div.
Cons: Seems like a hack - that's not the overflow
property's stated purpose.
我认为最好的方法是设置
clear:both
即将到来的元素。原因如下:
1)
:after
IE6 / 7不支持选择器,而FF3不支持选择器,但是,如果您只关心IE8 +和FF3.5 +的清除,:after可能最适合您...
2)
overflow
应该做其他事情,因此这种破解不够可靠。致作者的注意:清除没有任何技巧...清除意味着跳过浮动字段。自从有了HTML3(知道,甚至可能更长)以来,CLEAR就在我们这里。http: //www.w3.org/MarkUp/html3/deflists.html,也许他们应该选择与page类似的名称:new,但这仅是一个细节...