当您浮动元素时,您应该提供浮动元素的宽度。否则,您可能会在不同的浏览器中遇到意外的行为。
检查这个教程 http://www.ntutorials.com/css/understanding-floating,有关于 css 中浮动的好信息。 [链接已失效]
基本上,如果您提供overflow:hidden;
到容器 div 并为浮动元素提供宽度,您的问题将得到解决。
<div style="overflow: hidden;">
<div style="float:left; width: 300px;">Some text</div>
<div style="float:right; width: 300px;">Some text</div>
</div>
同样,您可以在想要规范化流程的任何位置添加另一个 div,如下所示:
<div>
<div style="float:left; width: 300px;">Some text</div>
<div style="float:right; width: 300px;">Some text</div>
<div style="clear:both;"></div>
<div>This div will be at the same place
as if the previous elements are not floated</div>
</div>
两者都可以工作:)
EDIT
我最近经常使用的另一种方法是浮动第一个元素并设置一个margin-left
到以下元素。例如:
<div>
<div style="float: left; width: 300px;">Some text</div>
<div style="margin-left: 300px;">Some text</div>
<div style="clear: both;"></div>
</div>
这种方法的优点是后面的元素(本例中是第二个 div)不需要固定宽度。另外,您可以跳过第三个 div (clear: both;
)。这是可选的。我只是添加它,以防浮动 div 的高度比第二个 div 长,因为如果不添加它,父 div 将始终获得第二个 div 的高度。