【问题标题】:How do I keep two side-by-side div elements the same height?如何保持两个并排的 div 元素高度相同?
【发布时间】:2011-03-01 04:17:00
【问题描述】:

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

【问题讨论】:

标签: html css html-table flexbox


【解决方案1】:

这是很多人都遇到过的常见问题,但幸运的是像Ed Eliot's on his blog这样的聪明人已经在网上发布了他们的解决方案。

基本上,您所做的是通过添加padding-bottom: 100% 使两个 div/列非常 高,然后使用 margin-bottom: -100%“欺骗浏览器”使其认为它们没有那么高。 Ed Eliot 在他的博客上对此进行了更好的解释,其中还包括许多示例。

.container {
    overflow: hidden;
}
.column {
    float: left;
    margin: 20px;
    background-color: grey;
    padding-bottom: 100%;
    margin-bottom: -100%;
}
<div class="container">

    <div class="column">
        Some content!<br>
        Some content!<br>
        Some content!<br>
        Some content!<br>
        Some content!<br>
    </div>

    <div class="column">
        Something
    </div>

</div>

【讨论】:

  • 对一个真实布局的解释有点差,但是在检查了第一个链接之后,我从他使用的一个示例中很好地实现了它。然而这真的很糟糕,因为您必须使用图像来表示列的底部边框,并且跨浏览器支持令人怀疑。但是它确实有效并且它不依赖于javascript,所以我将它标记为正确。谢谢!
  • 这似乎不适用于旧的 IE 浏览器(是的,不幸的是我仍然必须支持 IE6)。有什么办法让它兼容吗?
  • @strongriley Checkout Ed Eliot 的博客:ejeliot.com/blog/61 它应该可以在 IE6 中使用。也许问题是由其他地方引起的?
  • 如果窗口太窄并且 div 被放置在彼此下方,则会中断。
  • 如果padding-bottom 属性设置为100%,您如何定义实际希望出现在表格单元格中的单元格填充,例如padding: 7px 10px? (row 上我也需要 PS overflow:hidden
【解决方案2】:
<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 始终具有相同的高度。
【解决方案3】:

这是一个 CSS 从未真正有任何解决方案的领域——你只能使用 &lt;table&gt; 标签(或使用 CSS display:table* 值伪造它们),因为这是唯一一个“保留一堆相同高度的元素”已实现。

<div style="display: table-row;">

    <div style="border:1px solid #cccccc; display: table-cell;">
        Some content!<br/>
        Some content!<br/>
        Some content!<br/>
        Some content!<br/>
        Some content!<br/>
    </div>

    <div style="border:1px solid #cccccc;  display: table-cell;">
        Some content!
    </div>

</div>

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

【讨论】:

  • 此方案不适用于需要支持IE6/IE7的人,但我相信它是最干净的。
  • 这个答案是完美的!只是一个小提醒:可能会发生某些客户端需要“table”而不是“table-row”
  • @user2025810:哦,谢谢。你知道哪些客户需要table 而不是table-row
  • @user2025810: 哎呀,不能说我曾经测试过 :) 不过很高兴知道,干杯。 (鉴于它的 PDF 焦点,我敢打赌它支持 CSS 2.1 的一些与打印相关的功能,这些功能在浏览器中实现得不是很好。)
  • 有了这个解决方案 - 忘记在你的 div 中使用百分比 width,除非你在父元素上添加 display: table,这会搞砸。
【解决方案4】:

你可以使用 Jquery 的 Equal Heights Plugin 来完成,这个插件使所有的 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/

【讨论】:

    【解决方案5】:

    您可以使用 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

    【讨论】:

    • 如果&lt;div&gt; 都有动态内容,这将不起作用。我说的原因是如果&lt;div class="right"&gt; 有更多的内容,就会出现另一个问题。
    【解决方案6】:

    使用 jQuery

    ​​>

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

    // HTML
    <div id="columnOne">
    </div>
    
    <div id="columnTwo">
    </div>
    
    // Javascript
    $("#columnTwo").height($("#columnOne").height());
    

    使用 CSS

    这有点有趣。该技术称为Faux Columns。或多或少您实际上并没有将 实际 高度设置为相同,但是您装配了一些图形元素,使它们 看起来 高度相同。

    【讨论】:

    • 我认为使用 JavaScript 是一个非常好的方法。问题是 - 如果禁用它就会分崩离析。我想无论如何我都会使用它,并尽我所能建立最好的应急方案;--) 谢谢!
    • 这意味着 columnOne 的高度总是大于 columnTwo。
    • 您应该在应用高度之前比较列的高度。我认为js是解决这个问题最好的方法,几乎​​所有的浏览器都启用了js,如果没有,它们应该退出你的网站和许多其他网站。
    • 这也仅在页面首次加载时有效。如果窗口然后调整大小,导致 div 调整大小,那么它们将不会保持同步
    【解决方案7】:

    您可以使用Faux Columns

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

    但仅适用于固定宽度的框。

    经过充分测试,在每个浏览器中都能正常工作。

    【讨论】:

      【解决方案8】:

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

      在我看来,它远远优于 Faux Columns 和 One True Layout 的技术。

      一般的想法是带有position: absolute; 的元素将定位在最近的带有position: relative; 的父元素上。然后,您可以通过指定 top: 0px;bottom: 0px;(或您实际需要的任何像素/百分比)来拉伸一列以填充 100% 的高度。这是一个示例:

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

      【讨论】:

      • 如果右列比左列多,内容溢出。
      【解决方案9】:
          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);
      
          });
      

      【讨论】:

      • 请对您的回答提供任何评论。
      【解决方案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');
      });
      

      我希望这对你有用。

      【讨论】:

        【解决方案11】:

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

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

        【讨论】:

          【解决方案12】:

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

          【讨论】:

          • 我使用了 outerHeight 来包含填充和边框。这是我认为最干净的解决方案。
          • 我正在寻找的完美解决方案。其他解决方案适用于一行有几列的情况,但这种方法更适合复杂的 html 内容。小补充:在响应页面中调整文档大小时,内容高度不会因为固定而改变。所以,我添加了 $('.inner').css({ height: "initial" });在“每个函数”之前将高度设置为默认值。
          【解决方案13】:

          弹性盒

          对于 flexbox,它是一个声明:

          .row {
            display: flex; /* equal height of the children */
          }
          
          .col {
            flex: 1; /* additionally, equal width */
            
            padding: 1em;
            border: solid;
          }
          <div class="row">
            <div class="col">Lorem ipsum dolor sit amet, consectetur adipisicing elit.</div>
            <div class="col">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ad omnis quae expedita ipsum nobis praesentium velit animi minus amet perspiciatis laboriosam similique debitis iste ratione nemo ea at corporis aliquam.</div>
          </div>

          旧版浏览器可能需要前缀,请参阅browser support

          【讨论】:

          • flexbox 就像一个魅力。如果您正在开发响应式设计,并且希望您的第二个 div 在较小的屏幕上显示,则需要将 .row 设置为 display: block;在您的媒体查询中。
          • @NickZulu 我相信在这种情况下你应该设置flex-direction: column:jsfiddle.net/sdsgW/1
          • @Eckstein 这两种解决方案都不需要。查看演示。
          • 这对我不起作用,直到我添加了 height:100%;到子列
          • 是否可以让一个特定的子 div 确定另一个子 div 的高度?这样如果其他子 div 的内容发生变化,它就不能改变那个特定 div 的高度
          【解决方案14】:

          如果您不介意其中一个 divs 是大师并指定两个 divs 的高度,那么是这样的:

          Fiddle

          无论如何,右侧的div 会扩展或挤压&溢出以匹配左侧div 的高度。

          divs 都必须是容器的直接子级,并且必须在其中指定它们的宽度。

          相关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;
          }
          

          【讨论】:

            【解决方案15】:

            我知道这已经很长时间了,但无论如何我都会分享我的解决方案。 这是一个 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>
            

            【讨论】:

              【解决方案16】:

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

              };

              【讨论】:

                【解决方案17】:

                Fiddle

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

                【讨论】:

                  【解决方案18】:

                  这个问题在 6 年前就被问到了,但是现在用 flexbox 布局来给出一个简单的答案还是值得的。

                  只要给父&lt;div&gt;加上下面的CSS就行了。

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

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

                  【讨论】:

                  • @TylerH But ask 编辑了他的问题并添加了I'd like both boxes to always be the same size, so if one grows because text is placed into it, the other one should grow to match the height.,这在接受的答案中没有提到......我只是在这里完成了。也许我应该对接受的答案发表评论?
                  • 没有明确提及,因为它已经被简单的 CSS 声明所涵盖。全屏打开答案的片段并调整浏览器窗口的大小以查看;它们彼此保持相同的大小。
                  • 即使接受的答案使用 flexbox,这个也有不同的方法。 align-items:拉伸使我走上了在非常特殊的情况下解决问题的道路上。
                  • 不是align-items: stretch; flex 的默认值吗?
                  【解决方案19】:

                  我喜欢使用伪元素来实现这一点。您可以将其用作内容的背景,并让它们填满空间。

                  通过这些方法,您可以设置列、边框等之间的边距。

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

                  【讨论】:

                    【解决方案20】:

                    CSS 网格方式

                    这样做的现代方法(也避免必须在每两个项目周围声明一个&lt;div class="row"&gt;&lt;/div&gt;-wrapper)是使用 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>

                    【讨论】:

                      【解决方案21】:

                      我已经尝试了几乎所有上面提到的方法,但是 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;}
                      }
                      

                      上面的方法会等于cell的高度,对于手机或者平板这样的小屏幕,我们可以使用上面提到的@media方法。

                      【讨论】:

                        【解决方案22】:

                        使用 CSS Flexbox 和 min-height 对我有用

                        假设您有一个容器,里面有两个 div,并且您希望这两个 div 具有相同的高度。

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

                        然后只给子 div 的 'min-height' 为 100%

                        请看下面的代码

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

                        【讨论】:

                        • 我不需要最小高度:align-items:stretch;在 .row 中工作。
                        【解决方案23】:

                        我只是想添加到 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>
                        

                        【讨论】:

                          猜你喜欢
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          • 1970-01-01
                          相关资源
                          最近更新 更多