我有两个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>


当前回答

使用CSS Flexbox和min-height对我来说很有效

假设你有一个容器,里面有两个div,你想让这两个div有相同的高度。

你可以在容器上设置" display: flex "以及" align-items: stretch "

然后给孩子divs一个100%的“min-height”

请参阅下面的代码

.container { width: 100%; background: linear-gradient(red,blue); padding: 1em; /* important */ display: flex; /* important */ align-items: stretch; justify-content: space-around; } .child { width: 100%; background: white; color: grey; margin: 0 .5em; padding: .5em; /* important */ min-height: 100%; } <div class="container"> <div class="child"><p>This is some text to fill the paragraph</p></div> <div class="child"><p>This is a lot of text to show you that the other div will stretch to the same height as this one even though they do not have the same amount of text inside them. If you remove text from this div, it will shrink and so will the other div.</p></div> </div>

其他回答

我最近遇到了这个问题,我不太喜欢这个解决方案,所以我尝试了一下。

.mydivclass {inline-block;vertical-align:中间;宽度:33%;}

你可以使用Jquery的等高插件来完成,这个插件使所有的div的高度完全相同。如果其中一个生长了,其他的也会生长。

下面是一个实现示例

Usage: $(object).equalHeights([minHeight], [maxHeight]);

Example 1: $(".cols").equalHeights(); 
           Sets all columns to the same height.

Example 2: $(".cols").equalHeights(400); 
           Sets all cols to at least 400px tall.

Example 3: $(".cols").equalHeights(100,300); 
           Cols are at least 100 but no more than 300 pixels tall. Elements with too much content will gain a scrollbar.

这是链接

http://www.cssnewbie.com/equalheights-jquery-plugin/

在寻找这个答案的时候发现了这个帖子。我刚刚做了一个小jQuery函数,希望这有助于,工作就像一个魅力:

JAVASCRIPT

var maxHeight = 0;
$('.inner').each(function() {
    maxHeight = Math.max(maxHeight, $(this).height());
});
$('.lhs_content .inner, .rhs_content .inner').css({height:maxHeight + 'px'});

HTML

<div class="lhs_content">
    <div class="inner">
        Content in here
    </div>
</div>
<div class="rhs_content">
    <div class="inner">
        More content in here
    </div>
</div>

你可以使用伪列。

基本上,它使用包含DIV的背景图像来模拟两个等高DIV。使用这种技术还允许您添加阴影,圆角,自定义边界或其他时髦的模式到您的容器。

不过只适用于固定宽度的盒子。

经过良好的测试,在每个浏览器都能正常工作。

我几乎已经尝试了上面提到的所有方法,但是flexbox解决方案不能正确地与Safari一起工作,网格布局方法也不能正确地与旧版本的IE一起工作。

这个解决方案适合所有屏幕,并且是跨浏览器兼容的:

.container {margin:15px auto;}
.container ul {margin:0 10px;}
.container li {width:30%; display: table-cell; background-color:#f6f7f7;box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.25);}

@media (max-width: 767px){
    .container li { display: inline-block; width:100%; min-height:auto!important;}
}

上面的方法将等于单元格的高度,对于较小的屏幕,如手机或平板电脑,我们可以使用上面提到的@media方法。