html - 如何使容器的子 div 与 IE7 中最大的子 div 的宽度相匹配?

标签 html css internet-explorer-7

这似乎应该是重复的 - 我发现了许多类似的问题 - 但没有一个对我的有效答案。如果我遗漏了一个,请指出,我会删除这个。

我有一个包含多个子 div 的绝对定位的 div。我希望容器扩展到最宽的 child 的宽度,并且所有其他 child 扩展到相同的宽度。容器应具有最小宽度和最大高度;如果有太多 child ,它应该滚动。

所以这类似于组合下拉的行为,尽管这是在不同的上下文中使用的。

我想出的解决方案适用于 Chrome、Firefox 和 IE8,但不适用于 IE7(标准模式),其中子项不会扩展到容器的宽度。我尝试了一些改变,其中一些改变了 children 的 body ,但都导致了额外的问题。执行此操作的正确方法是什么?

我创建了以下示例来说明问题:

<html>
<head>
<style>

.container {
    display: block;
    position: absolute;
    top: 50px;
    left: 50px;
    min-width: 100px;
    max-height: 100px;
    border: 1px solid #999;
    overflow-x: hidden;
    overflow-y: auto;
}

.entry {
    display: block;
    width: auto;
    height: 20px;
    padding: 3px 20px 3px 5px;
    white-space: nowrap;
    background: #eee;
}

</style>
</head>
<body>
    <div class='container'>
        <div class='entry'><input type="checkbox"/>ABCDEFGHIJKLMNOPQRSTUVW</div>
        <div class='entry'><input type="checkbox"/>ABCDEFGHIJKLMNOPQRSTUVWXYZ</div>
        <div class='entry'><input type="checkbox"/>ABCDEFGHIJKLMNOPQRST</div>
        <div class='entry'><input type="checkbox"/>ABCDEFGHIJKLMNOPQ</div>
        <div class='entry'><input type="checkbox"/>ABCDEFGHIJKLMNOPQRST</div>
        <div class='entry'><input type="checkbox"/>ABCDEFGHIJKLMNOPQRSTUVW</div>
    </div>
</body>

最佳答案

在 IE7 中,父 div 需要为 width:100%width:auto 定义宽度才能在子元素上正常工作。不幸的是,在父级上定义宽度会适得其反,因为您希望父级尺寸相对于最大的子级是动态的,而不是静态的。

现在,这个浏览器怪癖可能无伤大雅,您可以忽略它并保留它,但是如果您希望您的网站在 IE7 中仍然看起来不错,您始终可以选择使用 JavaScript 将父级宽度设置为最大的子元素。

这是我使用的 JavaScript:

$(function() {
    /* function finds largest width of the .entry child of .container
    and assigns that width to the parent .container.
    This is for IE7 bug that requires a defined parent width in order for 
    width:auto to work on the children elements
    */
    var elemWidth = 0;
    var maxWidth = 0;
    $('.container')
        .find('.entry')
        .each(function() {
            // iterate through .entry and assign largest width to var elemWidth
            if ( $(this).width() > elemWidth ) {
            elemWidth = $(this).width();
            }
         });
    maxWidth = elemWidth + 30; // extra 30px spacing to compensate for y-overflow
    $('.container').width(maxWidth);
});

这是一个有效的 jsfiddle 示例:http://jsfiddle.net/qG8Qf/1/

关于html - 如何使容器的子 div 与 IE7 中最大的子 div 的宽度相匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5173444/

相关文章:

html - 下拉多个选项问题

ajax - Ajax使IE 7崩溃

html - ie7 li under li 而不是相同的高度

javascript - 动态创建的 radio 输入不检查 IE7

jquery - 按下回车键时 Bootstrap 3 模式关闭,但未提交表单

javascript - 浏览器 - 防止显示自动完成框?

html - 显示 inline-block 影响行高 hover

css - CSS Flexbox系统中的xs,md,lg是什么意思?

javascript - 带有设置了安全标志的 cookie 的 GET 请求

Python urllib,urllib2 填表