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


这是一个很多人都遇到过的常见问题,但幸运的是,一些聪明的人,如埃德·艾略特在他的博客上,已经在网上发布了他们的解决方案。

基本上你要做的就是通过添加padding-bottom: 100%使两个div /column都非常高,然后使用margin-bottom: -100%“欺骗浏览器”认为它们没有那么高。埃德·艾略特在他的博客上有更好的解释,其中也有很多例子。

.container { 溢出:隐藏; } .column { 浮:左; 保证金:20 px; 背景颜色:灰色; padding-bottom: 100%; margin-bottom: -100%; } < div class = "容器" > < div class = "列" > 一些内容!< br > 一些内容!< br > 一些内容!< br > 一些内容!< br > 一些内容!< br > < / div > < div class = "列" > 某物 < / div > < / div >


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

我在这里所做的是将高度更改为min-height,并给它一个固定的值。如果其中一个被调整大小,另一个将保持相同的高度。不知道这是不是你想要的


这是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。


你可以使用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轻松实现这一点。

CSS

.left, .right {border:1px solid #cccccc;}

jQuery

$(document).ready(function() {
    var leftHeight = $('.left').height();
    $('.right').css({'height':leftHeight});
});

HTML

   <div class="left">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi malesuada, lacus eu dapibus tempus, ante odio aliquet risus, ac ornare orci velit in sapien. Duis suscipit sapien vel nunc scelerisque in pretium velit mattis. Cras vitae odio sed eros mollis malesuada et eu nunc.</p>
   </div>
   <div class="right">
    <p>Lorem ipsum dolor sit amet.</p>
   </div>

你需要包含jQuery


使用jQuery

使用jQuery,您可以在一个超级简单的单行脚本中完成这个任务。

// HTML
<div id="columnOne">
</div>

<div id="columnTwo">
</div>

// Javascript
$("#columnTwo").height($("#columnOne").height());

使用CSS

这个更有趣一点。这种技术被称为人造柱。或多或少,你并没有设置实际的高度,但你设置了一些图形元素,让它们看起来一样高。


你可以使用伪列。

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

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

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


我很惊讶没有人提到(非常古老但可靠的)绝对列技术: http://24ways.org/2008/absolute-columns/

在我看来,它远远优于假列和一个真正的布局的技术。

一般的思想是一个具有位置的元素:绝对;将对最近的父元素进行定位,该父元素具有position: relative;然后通过赋值top: 0px;底部:0px;(或任何你实际需要的像素/百分比。)这里有一个例子:

<!DOCTYPE html>
<html>
  <head>
    <style>
      #container
      {
        position: relative;
      }

      #left-column
      {
        width: 50%;
        background-color: pink;
      }

      #right-column
      {
        position: absolute;
        top: 0px;
        right: 0px;
        bottom: 0px;
        width: 50%;
        background-color: teal;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <div id="left-column">
        <ul>
          <li>Foo</li>
          <li>Bar</li>
          <li>Baz</li>
        </ul>
      </div>
      <div id="right-column">
        Lorem ipsum
      </div>
    </div>
  </body>
</html>

    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);

    });

我有同样的问题,所以我创建了这个小函数使用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');
});

我希望这对你有用。


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

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


在寻找这个答案的时候发现了这个帖子。我刚刚做了一个小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>

Flexbox

对于flexbox,它是一个单一的声明:

.row { 显示:flex;/*儿童身高相等*/ } .col { flex: 1;/*另外,等于宽度*/ 填充:1 em; 边界:固体; } < div class = "行" > <div class="col">我与你同在,我与你同在</div> <div class="col">我爱你,我爱你,我爱你。</div> .</div> .</div> .</div> < / div >

旧浏览器可能需要前缀,请参阅浏览器支持。


如果你不介意其中一个divs是一个主人,并口述两个divs的高度,有这个:

小提琴

无论如何,右边的div会扩展或压缩&溢出来匹配左边的div的高度。

两个div都必须是容器的直接子节点,并且必须在容器中指定它们的宽度。

相关的CSS:

.container {
    background-color: gray;
    display: table;
    width: 70%;
    position:relative;
}

.container .left{
    background-color: tomato;
    width: 35%;
}

.container .right{
    position:absolute;
    top:0px;
    left:35%;
    background-color: orange;
    width: 65%;
    height:100%;
    overflow-y: auto;
}

我知道已经很长时间了,但我还是分享我的解决方案。 这是一个jQuery技巧。

——HTML

<div class="custom-column">
    <div class="column-left">
        asd
        asd<br/>
        asd<br/>
    </div>
    <div class="column-right">
        asd
    </div>
</div>

<div class="custom-column">
    <div class="column-left">
        asd
    </div>
    <div class="column-right">
        asd
        asd<br/>
        asd<br/>
    </div>
</div>

CSS——

<style>
.custom-column { margin-bottom:10px; }
.custom-column:after { clear:both; content:""; display:block; width:100%; }
    .column-left { float:left; width:25%; background:#CCC; }
    .column-right { float:right; width:75%; background:#EEE; }
</style>

——JQUERY

<script src="js/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $balancer = function() {
        $('.custom-column').each(function(){
            if($('.column-left',this).height()>$('.column-right',this).height()){
                $('.column-right',this).height($('.column-left',this).height())
            } else {
                $('.column-left',this).height($('.column-right',this).height())
            }

        });

    }
    $balancer();
    $(window).load($balancer());
    $(window).resize($balancer());

});
</script>

这是一个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] );

}

};


小提琴

HTML

<div class="container">

    <div class="left-column">

    </div>

    <div class="right-column">
        <h1>Hello Kitty!</h1>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium cum accusamus ab nostrum sit laborum eligendi, totam nam aperiam harum officia commodi tempora dolorum. Incidunt earum explicabo deleniti architecto illo!</p>
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laudantium cum accusamus ab nostrum sit laborum eligendi, totam nam aperiam harum officia commodi tempora dolorum. Incidunt earum explicabo deleniti architecto illo!</p>
    </div>

</div>

CSS

.container {
    float: left;
    width: 100%;
    background-color: black;
    position: relative;
    left: 0;
}

.container:before,
.container:after {
    content: " ";
    display: table;
}

.container:after {
    clear: both;
}

.left-column {
    float: left;
    width: 30%;
    height: 100%;
    position: absolute;
    background: wheat;
}

.right-column {
    float: right;
    width: 70%;
    position: relative;
    padding: 0;
    margin: 0;
    background: rebeccapurple;            
}

这个问题在6年前就被提出了,但在今天,它仍然值得用flexbox布局给出一个简单的答案。

只需添加以下CSS到父<div>,它将工作。

display: -webkit-flex;
display: flex;
flex-direction: row;
align-items: stretch;

前两行声明它将显示为flexbox。而flex-direction: row告诉浏览器它的子元素将显示在列中。align-items: stretch将满足这样的要求,即当其中一个子元素变高时,所有子元素将拉伸到相同的高度。


我喜欢使用伪元素来实现这一点。你可以使用它作为内容的背景,让它们填充空间。

使用这些方法,您可以设置列之间的边距,边框等。

.wrapper{ position: relative; width: 200px; } .wrapper:before, .wrapper:after{ content: ""; display: block; height: 100%; width: 40%; border: 2px solid blue; position: absolute; top: 0; } .wrapper:before{ left: 0; background-color: red; } .wrapper:after{ right: 0; background-color: green; } .div1, .div2{ width: 40%; display: inline-block; position: relative; z-index: 1; } .div1{ margin-right: 20%; } <div class="wrapper"> <div class="div1">Content Content Content Content Content Content Content Content Content </div><div class="div2">Other</div> </div>


CSS网格方式

这样做的现代方法(这也避免了必须在每两个项目周围声明一个<div class="row"></div>-包装器)将使用CSS网格。这也使您可以轻松控制项目行/列之间的间隙。

.grid-container { display: grid; grid-template-columns: repeat(2, 1fr); /* or simply "1fr 1fr;" */ grid-row-gap: 10px; grid-column-gap: 10px; } .grid-item { background-color: #f8f8f8; box-shadow: 0 0 3px #666; text-align: center; } .grid-item img { max-width: 100%; } <div class="grid-container"> <div class="grid-item">1 <br />1.1<br />1.1.1</div> <div class="grid-item">2</div> <div class="grid-item">3 <img src="https://lorempixel.com/420/320/abstract/1/Sample" alt="" /> 3.1 </div> <div class="grid-item">4</div> <div class="grid-item">5 <br />1.1<br />1.1.1</div> <div class="grid-item">6<img src="https://lorempixel.com/400/300/abstract/" alt="" /> 6.1</div> <div class="grid-item">7</div> <div class="grid-item">8</div> <div class="grid-item">9 <br />1.1<br />1.1.1</div> <div class="grid-item">10</div> <div class="grid-item">11 <img src="https://lorempixel.com/420/320/abstract/1/Sample" alt="" /> 11.1 </div> <div class="grid-item">12</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方法。


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


我只是想添加到Pavlo描述的伟大的Flexbox解决方案,在我的情况下,我有两个列表/列的数据,我想并排显示之间只有一点间距,水平居中封闭的div.通过在第一个(最左边)flex:1 div内嵌套另一个div,并将其浮动在右边,我得到了我想要的。我找不到任何其他方法来做到这一点,并在所有视口宽度上取得一致的成功:

<div style="display: flex;">
    <div style="flex: 1; padding-right: 15px;">
        <div style="float: right">
            <!-- My Left-hand side list of stuff -->
        </div>
    </div>

    <div style="flex: 1; padding-left: 15px;">
        <!-- My Right-hand side list of stuff -->
    </div>
</div>

第一步:设置父div的样式为display: flex

步骤2:设置你的子div样式为flex: 1和高度:100%

解释: Flex: 1将Flex -grow设置为1,这将平均分配容器的剩余空间给所有子容器。

下面是工作的jsfiddle链接

关于flex和父-子div在flex中的行为的更多细节,我建议访问这个链接:css-tricks