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


当前回答

你可以使用伪列。

基本上,它使用包含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] );

}

};

这是CSS从未真正有过任何解决方案的领域——你只能使用<table>标记(或使用CSS display:table* values伪造它们),因为这是唯一实现“保持一堆元素相同高度”的地方。

< span style=" font - family:宋体;"> < span style=" font - family:宋体;"显示:表格单元;" > 一些内容!< br / > 一些内容!< br / > 一些内容!< br / > 一些内容!< br / > 一些内容!< br / > < / div > < span style=" font - family:宋体;"显示:表格单元;" > 一些内容! < / div > < / div >

这适用于所有版本的Firefox, Chrome和Safari,至少版本8的Opera,以及版本8的IE。

你可以使用伪列。

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

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

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

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

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

使用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>