【问题标题】:How do I achieve equal height divs (positioned side by side) with HTML / CSS ?如何使用 HTML / CSS 实现等高 div(并排放置)?
【发布时间】:2010-11-06 13:44:49
【问题描述】:

我在一个容器中有两个 div。一个在左边,一个在右边,并排。即使它们的内容不同,我如何才能使它们具有相同的高度。

比如右边的div内容很多,而且是左边div的两倍高,如何让左边的div拉伸到右边div的高度?

是否有一些 JavaScript (jQuery) 代码来完成此操作?

【问题讨论】:

标签: javascript jquery css xhtml


【解决方案1】:

我同意最初的回答,但是带有 equal_heights() 方法的 JS 解决方案在某些情况下不起作用,假设您的产品彼此相邻。如果您仅将其应用于父容器,是的,它们将具有相同的高度,但如果一个不适合两行,产品名称部分可能会有所不同,这是我建议在下面使用的地方

https://jsfiddle.net/0hdtLfy5/3/

function make_children_same_height(element_parent, child_elements) {
    for (i = 0; i < child_elements.length; i++) {
    var tallest = 0;
    var an_element = child_elements[i];
    $(element_parent).children(an_element).each(function() {
      // using outer height since that includes the border and padding
      if(tallest < $(this).outerHeight() ){
        tallest = $(this).outerHeight();
      }
    });

    tallest = tallest+1; // some weird shit going on with half a pixel or something in FF and IE9, no time to figure out now, sowwy, hence adding 1 px
    $(element_parent).children(an_element).each(function() {
        $(this).css('min-height',tallest+'px');
    });
  }
}

【讨论】:

    【解决方案2】:

    这是我在纯 javascript 中使用的:

    看似很长,其实很简单!

    function equalizeHeights(elements){
        //elements as array of elements (obtain like this: [document.getElementById("domElementId"),document.getElementById("anotherDomElementId")]
    
        var heights = [];
        for (var i=0;i<elements.length;i++){
            heights.push(getElementHeight(elements[i],true));
        }
    
        var maxHeight =  heights[biggestElementIndex(heights)];
    
        for (var i=0;i<elements.length;i++){
            setElementHeight(elements[i],maxHeight,true);
        }
    }
    
    function getElementHeight(element, isTotalHeight){
        // isTotalHeight triggers offsetHeight
        //The offsetHeight property is similar to the clientHeight property, but it returns the height including the padding, scrollBar and the border.
        //http://stackoverflow.com/questions/15615552/get-div-height-with-plain-javascript
        {
            isTotalHeight = typeof isTotalHeight !== 'undefined' ? isTotalHeight : true;
        }
    
        if (isTotalHeight){
            return  element.offsetHeight;
        }else{
            return element.clientHeight;
        }
    }
    
     function setElementHeight(element,pixelHeight, setAsMinimumHeight){
    
        //setAsMinimumHeight: is set, we define the minimum height, so it can still become higher if things change...
        {
            setAsMinimumHeight = typeof setAsMinimumHeight !== 'undefined' ? setAsMinimumHeight : false;
        }
        var heightStr = "" + pixelHeight + "px";
        if (setAsMinimumHeight){
            element.style.minHeight = heightStr; // pixels
        }else{
            element.style.height = heightStr; // pixels
        }
    }
    
     function biggestElementIndex(arr){
        //http://stackoverflow.com/questions/11301438/return-index-of-greatest-value-in-an-array
        var max = arr[0];
        var maxIndex = 0;
    
        for (var i = 1; i < arr.length; i++) {
            if (arr[i] > max) {
                maxIndex = i;
                max = arr[i];
            }
        }
        return maxIndex;
    }
    

    【讨论】:

      【解决方案3】:

      虽然很多人不同意在这种类型的事情上使用 javascript,但我曾经使用过一种方法来单独使用 javascript 来实现这一点:

      var rightHeight = document.getElementById('right').clientHeight;
      var leftHeight = document.getElementById('left').clientHeight;
      if (leftHeight > rightHeight) {
      document.getElementById('right').style.height=leftHeight+'px';
      } else {
      document.getElementById('left').style.height=rightHeight+'px';
      }
      

      “left”和“right”是两个 div 标签的 id。

      【讨论】:

        【解决方案4】:

        你可以用 js 让它工作:

        <script>
            $(document).ready(function() {
                var height = Math.max($("#left").height(), $("#right").height());
                $("#left").height(height);
                $("#right").height(height);
            });
        </script>
        

        【讨论】:

        • 哇真的很喜欢这个Andi,如果在浏览器宽度改变时刷新它会更好。调整大小时,高度保持不变。
        • @Andi P. Trix 你好!这工作正常,但如果我尝试调整屏幕大小不会自动更改,我必须刷新才能看到结果。某种方式来动态地做到这一点?提前谢谢朋友!
        【解决方案5】:

        可以使用 jQuery,但有更好的方法来做到这一点。

        这类问题出现很多,一般有3个答案...

        1. Use CSS

        这是做到这一点的“最佳”方法,因为它是语义上最纯粹的方法(无需求助于 JS,它有其自身的问题)。最好的方法是使用display: table-cell 和相关值。您也可以尝试使用the faux background technique(您可以使用 CSS3 渐变)。

        2. Use Tables

        这似乎工作得很好,但代价是没有语义的布局。你也会引起纯粹主义者的轰动。我几乎避免使用表格,你也应该这样做。

        3. Use jQuery / JavaScript

        这有利于拥有最多的语义标记,除非禁用 JS,否则您将无法获得所需的效果。

        【讨论】:

        • #2 的替代方案:display:table。但是,我注意到表格存在问题,即它们不能正确过渡。所以,CSS3 + 表格 = 不可以
        • 第二个链接失效了
        • @alex 使用 flexbox 也可能是另一种解决方案。见stackoverflow.com/questions/22253122/…
        【解决方案6】:

        这是一个非常简单的解决方案,带有简短的 css display:table

        <div id="main" class="_dt-no-rows">
          <div id="aside" contenteditable="true">
            Aside
            <br>
            Here's the aside content
          </div>
          <div id="content" contenteditable="true">
            Content
            <br>
            geht's pellentesque wurscht elementum semper tellus s'guelt Pfourtz !. gal hopla
            <br>
            TIP : Just clic on this block to add/remove some text
          </div>
        </div>
        

        这里是css

        #main {
         display: table;
         width: 100%;
        }
        #aside, #content {
          display: table-cell;
          padding: 5px;
        }
        #aside {
          background: none repeat scroll 0 0 #333333;
          width: 250px;
        }
        #content {
        background: none repeat scroll 0 0 #E69B00;
        }
        

        它看起来像这样

        【讨论】:

          【解决方案7】:

          我已经看到很多尝试这样做,但没有一个能满足我的强迫症需求。尽管这比使用 JavaScript 更好。

          已知的缺点:

          • 在具有动态宽度的容器的情况下不支持多个元素行。
          • 在 IE6 中不起作用。

          基地:

          • red 是(辅助)容器,用于设置内容的边距。
          • greenposition: relative; overflow: hidden 和(可选,如果您希望列居中)text-align: center; font-size: 0; line-height: 0;
          • 蓝色 display: block; float: left; 或(可选,如果您希望列居中)display: inline-block; vertical-align: top;

          到目前为止,没有什么不寻常的。无论 blue 元素有什么内容,都需要添加一个绝对定位的元素(yellow;注意这个元素的z-index必须低于实际的蓝框的内容)用这个元素设置top: 0; bottom: 0;(不要设置左右位置)。

          您的所有元素现在都具有相同的高度。对于大多数布局,这已经足够了。我的场景需要动态内容后跟静态内容,其中静态内容必须在同一行。

          为此,您需要将padding-bottom (dark green) eq 添加到 blue 元素的固定高度内容中。

          然后在 yellow 元素内创建另一个绝对定位 (left: 0; bottom: 0;) 元素(深蓝色)。

          假设,如果这些框(黄色)必须是活动超链接,并且您有任何想要应用于原始蓝色框的样式,则可以使用相邻兄弟选择器:

          yellow:hover + blue {}
          

          这是代码和demo

          HTML:

          <div id="products">
              <ul>
                  <li class="product a">
                      <a href="">
                          <p class="name">Ordinary product description.</p>
                          <div class="icon-product"></div>
                      </a>
                      <p class="name">Ordinary product description.</p>
                  </li>
                  <li class="product b">
                      <a href="">
                          <p class="name">That lenghty product description or whatever else that does not allow you have fixed height for these elements.</p>
                          <div class="icon-product"></div>
                      </a>
                      <p class="name">That lenghty product description or whatever else that does not allow you have fixed height for these elements.</p>
                  </li>
                  <li class="product c">
                      <a href="">
                          <p class="name">Another ordinary product description.</p>
                          <div class="icon-product"></div>
                      </a>
                      <p class="name">Another ordinary product description.</p>
                  </li>
              </ul>
          </div>
          

          SCSS/LESS:

          #products { 
              ul { position: relative; overflow: hidden; text-align: center; font-size: 0; line-height: 0;  padding: 0; margin: 0;
                  li { display: inline-block; vertical-align: top; width: 130px; padding: 0 0 130px 0; margin: 0; }
              }
          
              li {
                  a { display: block; position: absolute; width: 130px; background: rgba(255,0,0,.5); z-index: 3; top: 0; bottom: 0;
                      .icon-product { background: #ccc; width: 90px; height: 90px; position: absolute; left: 20px; bottom: 20px; }
                      .name { opacity: 1; }
                  }
          
                  .name { position: relative; margin: 20px 10px 0; font-size: 14px; line-height: 18px; opacity: 0; }
          
                  a:hover {
                      background: #ddd; text-decoration: none;
          
                      .icon-product { background: #333; }
                  }
              }
          }
          

          请注意,该演示使用涉及数据复制的解决方法来修复z-index。或者,您可以使用pointer-events: none 以及任何适用于 IE 的解决方案。

          【讨论】:

            【解决方案8】:

            在 jquery 文档准备功能中使用它。考虑到有两个 div 的 id 分别为“left”和“right”。

            var heightR = $("#right").height();
            var heightL = $("#left").height();
            
            if(heightL > heightR){
                $("#right").css({ height: heightL});
            } else {
                $("#left").css({ height: heightR});
            }
            

            【讨论】:

              【解决方案9】:

              这是一种使用纯 CSS 的方法,但是,正如您在示例中所注意到的(适用于 IE 7 和 Firefox),边框可能很困难 - 但它们并非不可能,所以这完全取决于你想做。这个例子假设了一个相当常见的 CSS 结构体 > 包装器 > 内容容器 > 第 1 列和第 2 列。

              关键是底部边距及其取消填充。

              <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
              <html xmlns="http://www.w3.org/1999/xhtml">
              <head>
              <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
              <title>Equal Height Columns</title>
              <style type="text/css">
              <!--
              * { padding: 0; margin: 0; }
              #wrapper { margin: 10px auto; width: 600px; }
              #wrapper #main_container { width: 590px; padding: 10px 0px 10px 10px; background: #CCC; overflow: hidden; border-bottom: 10px solid #CCC; }
              #wrapper #main_container div { float: left; width: 263px; background: #999; padding: 10px; margin-right: 10px; border: 1px solid #000; margin-bottom: -1000px; padding-bottom: 1000px; }
              #wrapper #main_container #right_column { background: #FFF; }
              -->
              </style>
              </head>
              
              <body>
              <div id="wrapper">
                  <div id="main_container">
                      <div id="left_column">
                          <p>I have two divs inside of a container. One on the left, one on the right, side by side. How am I able to make each one be of equal height, even though they have different content.</p>
                      </div><!-- LEFT COLUMN -->
                      <div id="right_column">
                        <p>I have two divs inside of a container. One on the left, one on the right, side by side. How am I able to make each one be of equal height, even though they have different content.</p>
                        <p>&nbsp;</p>
                        <p>For example, the right div has a lot of content, and is double the height of the left div, how do I make the left div stretch to the same height of the right div?</p>
                        <p>&nbsp;</p>
                        <p>Is there some JavaScript (jQuery) code to accomplish this?</p>
                      </div><!-- RIGHT COLUMN -->
                  </div><!-- MAIN CONTAINER -->
              </div><!-- WRAPPER -->
              </body>
              </html>
              

              看起来是这样的:

              【讨论】:

              • 一个非常有趣的解决方案!遗憾的是,如果您更改 #wrapper #main_container div{width: 263px - > 50% },它将无法正常工作
              【解决方案10】:

              还有一个名为 equalHeights 的 jQuery 插件,我使用它取得了一些成功。

              我不确定我使用的是上面提到的灯丝组中的那个,还是this one that was the first google result...无论哪种方式,jquery 插件都可能是最简单、最灵活的方法。

              【讨论】:

                【解决方案11】:

                好吧,我不会做大量的 jQuery,但在 CSS/Javascript 世界中,我只会使用对象模型并编写如下语句:

                if(leftDiv.style.height > rightDive.style.height)
                   rightDiv.style.height = leftDiv.style.height;
                else
                   leftDiv.style.height = rightDiv.style.height)
                

                【讨论】:

                • 您可以在这里使用Math.max(),并将它们都设置为它。也许更优雅。
                • 在 2009 年编写时已经足够好,但响应式布局变得更加复杂。
                • 您在 7 年后严重否决了一个答案,因为技术不同?
                • 我需要找到一个非 jquery 方法来做到这一点。这个线程出现在谷歌搜索上。就像凌晨 2 点一样,我对反对票的进攻感到不利。
                猜你喜欢
                • 2010-11-13
                • 1970-01-01
                • 2011-02-07
                • 2014-09-02
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                相关资源
                最近更新 更多