12

我想创建一个带有标题栏的简单框,其中包含标题和一些工具按钮。我有以下标记:

<div style="float:left">
    <div style="background-color:blue; padding: 1px; height: 20px;">
        <div style="float: left; background-color:green;">title</div>
        <div style="float: right; background-color:yellow;">toolbar</div>
    </div>
    <div style="clear: both; width: 200px; background-color: red;">content</div>
</div>

这在 Firefox 和 Chrome 中表现良好:

http://www.boplicity.nl/images/firefox.jpg

然而 IE7 完全搞砸了,把右边的浮动元素放在页面的右边:

http://www.boplicity.nl/images/ie7.jpg

这可以解决吗?

4

6 回答 6

23

指定最外层 div 的宽度。如果你的内容 div 中的宽度意味着这是你的盒子的总宽度,只需将它添加到最外层的 div,并(可选)将它从内容中删除,如下所示:

<div style="float:left; width: 200px;">
    <div style="background-color:blue; padding: 1px; height: 20px;">
        <div style="float: left; background-color:green;">title</div>
        <div style="float: right; background-color:yellow;">toolbar</div>
    </div>
    <div style="clear: both; background-color: red;">content</div>
</div>
于 2008-10-09T13:46:23.977 回答
3

这只是一个快速的答案,所以如果它不起作用,我会举手。我认为如果您只添加最小宽度而不是宽度,Marko 的解决方案可能会起作用。如果您也想迎合 ie6,则可能需要使用 hack,因为 ie6 及其后代不支持最小宽度。

所以这应该适用于 IE7 和其他现代浏览器。将最小宽度设置为合适的值。

<div style="float:left; min-width: 200px;">
    <div style="background-color:blue; padding: 1px; height: 20px;">
        <div style="float: left; background-color:green;">title</div>
        <div style="float: right; background-color:yellow;">toolbar</div>
    </div>
    <div style="clear: both; background-color: red;">content</div>
</div>
于 2008-10-09T15:37:17.997 回答
2

我使用 jQuery 修复了它以模拟非 IE 浏览器的行为:

    // IE fix for div widths - size header to width of content
    if (!$.support.cssFloat) {
        $("div:has(.boxheader) > table").each(function () {
                $(this).parent().width($(this).width());
        });
    }
于 2009-06-24T19:39:19.840 回答
1

尝试放入position:relative;父元素和子元素。它为我解决了这个问题。

于 2010-11-13T19:42:27.580 回答
1

最近知道,正确的浮动元素需要在其他元素之前附加 div。这是最简单的修复,无需添加任何更改。

<div style="background-color:blue; padding: 1px; height: 20px;">
    <div style="float: right; background-color:green;">title</div>
    <div style="float: left; background-color:yellow;">toolbar</div>
</div>
于 2012-01-06T15:19:25.603 回答
-2

使其<div style="background-color:blue; padding: 1px; height: 20px;>成为 2 个浮动 div 的父级clear:all

于 2008-10-09T13:45:42.293 回答