这似乎应该是重复的 - 我发现了很多类似的问题 - 但没有一个对我的答案有效。如果我漏掉了一个,请指出,我会删除这个。
我有一个绝对定位的 div 包含几个子 div。我希望容器扩展到最宽子级的宽度,并且所有其他子级扩展到相同的宽度。容器应有最小宽度和最大高度;如果有太多孩子,它应该滚动。
因此,这类似于组合下拉列表的行为,尽管这是在不同的上下文中使用的。
我提出的解决方案适用于 Chrome、Firefox 和 IE8,但不适用于 IE7(标准模式),其中子项不会扩展到容器的宽度。我尝试了许多改变,其中一些使孩子们成长,但所有这些都导致了额外的问题。这样做的正确方法是什么?
我创建了以下示例来说明该问题:
<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%
or 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/ http://jsfiddle.net/qG8Qf/1/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)