我有两个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>
在寻找这个答案的时候发现了这个帖子。我刚刚做了一个小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>
这是一个jQuery插件,它为同一行上的所有元素设置相等的高度(通过检查元素的offset.top)。因此,如果你的jQuery数组包含来自多个行(不同的offset.top)的元素,每一行将有一个独立的高度,基于该行最大高度的元素。
jQuery.fn.setEqualHeight = function(){
var $elements = [], max_height = [];
jQuery(this).css( 'min-height', 0 );
// GROUP ELEMENTS WHICH ARE ON THE SAME ROW
this.each(function(index, el){
var offset_top = jQuery(el).offset().top;
var el_height = jQuery(el).css('height');
if( typeof $elements[offset_top] == "undefined" ){
$elements[offset_top] = jQuery();
max_height[offset_top] = 0;
}
$elements[offset_top] = $elements[offset_top].add( jQuery(el) );
if( parseInt(el_height) > parseInt(max_height[offset_top]) )
max_height[offset_top] = el_height;
});
// CHANGE ELEMENTS HEIGHT
for( var offset_top in $elements ){
if( jQuery($elements[offset_top]).length > 1 )
jQuery($elements[offset_top]).css( 'min-height', max_height[offset_top] );
}
};