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

<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

可以修复吗?

有帮助吗?

解决方案

指定最外层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>

其他提示

这只是一个快速的答案,所以如果它不能正常工作,我会举起手来。我认为如果你只是添加min-width而不是width,Marko的解决方案可能会有效。如果你也试图迎合ie6,你可能需要使用hack,因为ie6及其后代不支持min width。

所以这应该适用于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>

我使用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());
        });
    }

尝试将position:relative;放到parent-element和child-element中。它解决了我的问题。

最近了解到,右侧浮动元素需要在其他元素之前附加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>

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top