如何使并排的两个div元素保持相同的高度?

544

我有两个并排的div元素。我希望它们的高度相同,并且在一个调整大小时保持相同。如果其中一个因为放置文本而增长,则另一个应该增长以匹配高度。但我无法想出解决办法,有什么建议吗?

<div style="overflow: hidden">
    <div style="
        border: 1px solid #cccccc;
        float: left;
        padding-bottom: 1000px;
        margin-bottom: -1000px;
    ">
        Some content!<br />
        Some content!<br />
        Some content!<br />
        Some content!<br />
        Some content!<br />
    </div>

    <div style="
        border: 1px solid #cccccc;
        float: left;
        padding-bottom: 1000px;
        margin-bottom: -1000px;
    ">
        Some content!
    </div>
</div>


你希望如果其中一个变大了,另一个保持相同的高度尺寸吗? - Wai Wong
一个示例,它不是一个解决方案,但可以在可编辑的环境中找到:http://jsfiddle.net/PCJUQ/ - MvanGeest
24个回答

-1
    var numexcute = 0;
    var interval;
    $(document).bind('click', function () {

        interval = setInterval(function () {
            if (numexcute >= 20) {
                clearInterval(interval);
                numexcute = 0;
            }
            $('#leftpane').css('height', 'auto');
            $('#rightpane').css('height', 'auto');
            if ($('#leftpane').height() < $('#rightpane').height())
                $('#leftpane').height($('#rightpane').height());
            if ($('#leftpane').height() > $('#rightpane').height())

                $('#rightpane').height($('#leftpane').height());
            numexcute++;
        }, 10);

    });

2
请将以下与编程有关的内容从英语翻译成中文。只返回翻译后的文本:如果需要,请附上您的解释。 - sgnsajgon

-1

我曾经遇到同样的问题,所以我使用jQuery创建了这个小函数,因为现在jQuery已经成为每个Web应用程序的一部分。

function fEqualizeHeight(sSelector) {
    var sObjects = $(sSelector);

    var iCount = sObjects.length;

    var iHeights = [];

    if (iCount > 0) {
        $(sObjects).each(function () {
            var sHeight = $(this).css('height');
            var iHeight = parseInt(sHeight.replace(/px/i,''));
            iHeights.push(iHeight);
        });

        iHeights.sort(function (a, b) {
            return a - b
        });

        var iMaxHeight = iHeights.pop();

        $(sSelector).each(function () {
            $(this).css({
                'height': iMaxHeight + 'px'
            });
        });
    }
}

您可以在页面准备就绪事件上调用此函数

$(document).ready(function(){
   fEqualizeHeight('.columns');
});

我希望这对你有用。

-3

最近我发现这个问题,但并不是很喜欢已有的解决方案,所以我尝试了一些实验。

.mydivclass {inline-block; vertical-align: middle; width: 33%;}


-4
<div>

<div style="border:1px solid #cccccc; float:left; min-height:200px;">

Some content!<br/>
Some content!<br/>
Some content!<br/>
Some content!<br/>
Some content!<br/>

</div>

<div style="border:1px solid #cccccc; float:left; min-height:200px;">

Some content!

</div>

</div>

我在这里所做的是将高度更改为最小高度,并给它一个固定值。如果其中一个被调整大小,另一个将保持相同的高度。不确定这是否符合您的要求。

OP希望div始终具有相同的高度。 - Simon Forsberg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接