【问题标题】:HTML/CSS: Making two floating divs the same heightHTML/CSS:使两个浮动 div 具有相同的高度
【发布时间】:2010-11-15 08:45:19
【问题描述】:

我目前使用table 解决了一个小问题,见下文。基本上,我想让两个 div 占据 100% 的可用宽度,但只占用所需的垂直空间(这在图片中并不是那么明显)。如图所示,两者应始终具有完全相同的高度并在它们之间留一条小线。


(来源:pici.se

使用table 很容易做到这一点,我目前正在这样做。但是,我不太热衷于解决方案,因为从语义上讲,这实际上不是一个表格。

【问题讨论】:

标签: html css html-table


【解决方案1】:

您可以通过应用大量的底部填充、相同数量的底部负边距并用隐藏溢出的 div 围绕列来在 CSS 中获得等高的列。将文本垂直居中有点棘手,但这应该对您有所帮助。

#container {
  overflow: hidden;
      width: 100%;
}
#left-col {
  float: left;
  width: 50%;
  background-color: orange;
  padding-bottom: 500em;
  margin-bottom: -500em;
}
#right-col {
  float: left;
  width: 50%;
  margin-right: -1px; /* Thank you IE */
  border-left: 1px solid black;
  background-color: red;
  padding-bottom: 500em;
  margin-bottom: -500em;
}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

<head></head>

<body>
  <div id="container">
    <div id="left-col">
      <p>Test content</p>
      <p>longer</p>
    </div>
    <div id="right-col">
      <p>Test content</p>
    </div>
  </div>
</body>

我认为值得一提的是,streetpc 之前的答案包含无效的 html,文档类型是 XHTML,并且属性周围有单引号。另外值得注意的是你不需要一个带有clear的额外元素来清除容器的内部浮动。如果你使用溢出隐藏,这会清除所有非 IE 浏览器中的浮动,然后只需添加一些东西给 hasLayout,例如 width 或 zoom:1 将导致 IE 清除其内部浮动。

我已经在所有现代浏览器 FF3+ Opera9+ Chrome Safari 3+ 和 IE6/7/8 中对此进行了测试。这可能看起来像一个丑陋的技巧,但效果很好,我在生产中经常使用它。

我希望这会有所帮助。

【讨论】:

  • 我给出的代码在 W3C 的验证器上验证(好吧,一旦你添加了一个 元素,这不是你的重点)。此外,根据此讨论,规范允许使用单引号:<a href="/default/index/tourl?u=aHR0cDovL3d3dy5zaXRlcG9pbnQuY29tL2ZvcnVtcy9zaG93dGhyZWFkLnBocD90PTU0MjczIzY%3D" rel="nofollow" target="_blank">sitepoint.com/forums/showthread.php?t=54273#6</a>
  • 抱歉,我的错误。我已经修改了上面的答案。但是请注意,使用您的方法,如果右列比左列大,则红色显示在下方,因为这两个框的高度不完全正确。根据设计,我会选择人造列或带有底部边距和填充的这种方法。
  • 实际上,虽然 Kevin C. 给出的关于阴影被切断的解决方案适用于顶部、左侧和右侧的填充,但它不适用于底部。目前还没找到解决办法。
  • 干得好,娜塔莉。 @laarsk 不可预测的高度正是它的用途,不是吗?查看演示:jsfiddle.net/RT3MT/4 移动“更长”的段落以查看
  • 这是我见过的最丑陋的 CSS hack 之一,但我会张开双臂拥抱它,哈哈。这似乎是唯一的出路
【解决方案2】:

现在是 2012+n 年,所以如果您不再关心 IE6/7,display:tabledisplay:table-rowdisplay:table-cell 可以在所有现代浏览器中使用:

http://www.456bereastreet.com/archive/200405/equal_height_boxes_with_css/

2016-06-17 更新:如果您认为 display:flex 的时机已到,请查看 Flexbox Froggy

【讨论】:

  • 这个答案换成display: flex会是哪一年?
  • 不,我们现在是 2014 年(;
  • aaaaaa 而且现在是 2015 年,也许到年底我们可以将答案更改为 display: flex :)
  • 我还生活在 1950 年代。
  • 2016 年您好!我们现在可以使用 flex
【解决方案3】:

您应该使用 flexbox 来实现这一点。它在 IE8 和 IE9 中不受支持,并且仅在 IE10 中带有 -ms 前缀,但所有其他浏览器都支持它。对于供应商前缀,您还应该使用autoprefixer

.parent {
    display: flex;
    flex-wrap: wrap; // allow wrapping items
}

.child {
    flex-grow: 1;
    flex-basis: 50%; // 50% for two in a row, 33% three in a row etc.
}

【讨论】:

  • 我对 flex 的问题是它需要一个围绕列的包装器。使用 floats + display:table 技术,我可以拥有例如一个标题和一堆列,效果在列上起作用而不影响标题。
【解决方案4】:

您可以使用 js 来实现这一点:

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

【讨论】:

  • 请注意这个问题已经很老了,并且已经提供了更好的解决方案(不需要javascript)。
  • 我其实很喜欢这个解决方案。这很有趣,并且表明您不仅可以使用 css 操作 html,还可以在 jquery 的帮助下进行操作
  • 如果列的高度发生变化,此解决方案将不起作用。如果更改列的内容,则可能会发生这种情况。需要运行此功能:内容更改和 .on 浏览器调整大小。 css 方法更理想,因为它避免了这些问题
【解决方案5】:

这是 CSS 中的经典问题。没有真正的解决方案。

This article from A List Apart 是这个问题的好读物。它使用一种称为“假列”的技术,基于在包含列的元素上具有一个垂直平铺的背景图像,从而产生等长列的错觉。由于它位于浮动元素的包装器上,因此它与最长的元素一样长。


A List Apart 编辑在这篇文章中有这样的注释:

编者注:虽然这篇文章在当时非常出色,但可能无法反映现代最佳实践。

该技术需要完全静态的宽度设计,不能很好地与当今跨设备网站流行的流动布局和响应式设计技术配合使用。然而,对于静态宽度的网站,这是一个可靠的选择。

【讨论】:

  • 谢谢,这似乎是一个不错的 hack。但是,我忘了提到右列应该有文本,垂直居中。我是否相信人造列不能做到这一点?
【解决方案6】:

我有类似的问题,我认为最好的选择是使用一点点 javascript 或 jquery。

您可以通过获取最高 div 值并将该值应用于所有其他 div 来使想要的 div 具有相同的高度。如果您有许多 div 和许多解决方案,我建议您编写一些高级 js 代码来找出所有 div 中哪个是最高的,然后使用它的值。

使用 jquery 和 2 个 div 非常简单,这里是示例代码:

$('.smaller-div').css('height',$('.higher-div').css('height'));

最后,还有最后一件事。 它们的填充(顶部和底部)必须相同!如果一个有更大的填充,你需要消除填充差异。

【讨论】:

    【解决方案7】:

    据我所知,您无法使用当前的 CSS 实现来做到这一点。要制作两列,等高,您需要 JS。

    【讨论】:

      【解决方案8】:

      这适用于 IE 7、FF 3.5、Chrome 3b、Safari 4 (Windows)。

      如果您取消注释底部更清晰的 div,也可以在 IE 6 中使用。 编辑:正如 Natalie Downe 所说,您只需将 width: 100%; 添加到 #container 即可。

      <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
          "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
      <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
      <head>
          <style type="text/css">
              #container {
                  overflow: hidden;
                  border: 1px solid black;
                  background-color: red;
              }
              #left-col {
                  float: left;
                  width: 50%;
                  background-color: white;
              }
              #right-col {
                  float: left;
                  width: 50%;
                  margin-right: -1px; /* Thank you IE */
              }
          </style>
      </head>
      <body>
          <div id='container'>
              <div id='left-col'>
                  Test content<br />
                  longer
              </div>
              <div id='right-col'>
                  Test content
              </div>
              <!--div style='clear: both;'></div-->
          </div>
      </body>
      </html>
      

      如果 div 的高度不是固定的,我不知道在右侧 div 中垂直居中文本的 CSS 方法。如果是,您可以将 line-height 设置为与 div 高度相同的值,并使用 display: inline; line-height: 110% 放置一个包含您的文本的内部 div。

      【讨论】:

        【解决方案9】:

        使用 Javascript,您可以使两个 div 标签的高度相同。使用下面显示的代码,较小的 div 将调整为与最高的 div 标签相同的高度:

        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。

        【讨论】:

          【解决方案10】:

          通过使用 css 属性 --> display:table-cell

          div {
              border: 1px solid #000;
              margin: 5px;
              padding: 4px;
          	display:table-cell;
          	width:25%	;position:relative;
          }
          body{display:table;
          	border-collapse:separate;
          	border-spacing:5px 5px}
          <div>
              This is my div one This is my div one This is my div one
          </div>
          <div>
              This is my div two This is my div two This is my div two This is my div two This is my div two This is my div two
          </div>
          <div>
              This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3 This is my div 3
          </div>

          【讨论】:

            【解决方案11】:

            使用 JS,在所有想要具有相同高度的元素中使用data-same-height="group_name"

            例子: https://jsfiddle.net/eoom2b82/

            代码:

            $(document).ready(function() {
                var equalize = function () {
                    var disableOnMaxWidth = 0; // 767 for bootstrap
            
                    var grouped = {};
                    var elements = $('*[data-same-height]');
            
                    elements.each(function () {
                        var el = $(this);
                        var id = el.attr('data-same-height');
            
                        if (!grouped[id]) {
                            grouped[id] = [];
                        }
            
                        grouped[id].push(el);
                    });
            
                    $.each(grouped, function (key) {
                        var elements = $('*[data-same-height="' + key + '"]');
            
                        elements.css('height', '');
            
                        var winWidth = $(window).width();
            
                        if (winWidth <= disableOnMaxWidth) {
                            return;
                        }
            
                        var maxHeight = 0;
            
                        elements.each(function () {
                            var eleq = $(this);
                            maxHeight = Math.max(eleq.height(), maxHeight);
                        });
            
                        elements.css('height', maxHeight + "px");
                    });
                };
            
                var timeout = null;
            
                $(window).resize(function () {
                    if (timeout) {
                        clearTimeout(timeout);
                        timeout = null;
                    }
            
                    timeout = setTimeout(equalize, 250);
                });
                equalize();
            });
            

            【讨论】:

              【解决方案12】:

              我需要做类似的事情,这是我的实现。回顾一下目的,它是让 2 个元素占据给定父容器的宽度,并且高度只达到它需要的高度。基本上高度等于最大内容量的最大高度,但另一个容器是齐平的。

              html

              <div id="ven">
              <section>some content</section>
              <section>some content</section>
              </div>
              

              css

              #ven {
              height: 100%;
              }
              #ven section {
              width: 50%;
              float: left;
              height: 100%;
              }
              

              【讨论】:

                【解决方案13】:

                几年前,float 属性曾使用table 方法解决该问题,该方法使用display: table;display: table-row;display: table-cell;

                但是现在有了 flex 属性,你可以用 3 行代码解决它:display: flex;flex-wrap: wrap;flex: 1 0 50%;

                .parent {
                    display: flex;
                    flex-wrap: wrap;
                }
                
                .child {
                 // flex: flex-grow flex-shrink flex-basis;
                    flex: 1 0 50%;
                }
                

                1 0 50% 是我们给的flex 值:flex-grow flex-shrink flex-basis。这是 flexbox 中一个相对较新的快捷方式,可以避免单独键入它们。我希望这对那里的人有所帮助

                【讨论】:

                  【解决方案14】:

                  考虑到 Natalie 的回复,它看起来非常好,但我遇到了可能的页脚区域的问题,可以使用 clear: both 稍微破解一下。

                  当然,现在更好的解决方案是使用 flexbox 或网格。

                  如果你愿意,可以查看codepen

                  .section {
                    width: 500px;
                    margin: auto;
                    overflow: hidden;
                    padding: 0;
                  }
                  
                  div {
                    padding: 1rem;
                  }
                  
                  .header {
                    background: lightblue;
                  }
                  
                  .sidebar {
                    background: lightgreen;
                    width: calc(25% - 1rem);
                  }
                  
                  .sidebar-left {
                    float: left;
                    padding-bottom: 500rem;
                    margin-bottom: -500rem;
                  }
                  
                  .main {
                    background: pink;
                    width: calc(50% - 4rem);
                    float: left;
                    padding-bottom: 500rem;
                    margin-bottom: -500rem;
                  }
                  
                  .sidebar-right {
                    float: right;
                    padding-bottom: 500rem;
                    margin-bottom: -500rem;
                  }
                  
                  .footer {
                    background: black;
                    color: white;
                    float: left;
                    clear: both;
                    margin-top: 1rem;
                    width: calc(100% - 2rem);
                  }
                  <div class="section">
                  <div class="header">
                    This is the header
                  </div>
                  <div class="sidebar sidebar-left">
                    This sidebar could have a menu or something like that. It may not have the same length as the other
                  </div>
                  <div class="main">
                    This is the main area. It should have the same length as the sidebars
                  </div>
                  <div class="sidebar sidebar-right">
                    This is the other sidebar, it could have some ads
                  </div>
                  <div class="footer">
                    Footer area
                  </div>
                  </div>

                  【讨论】:

                    猜你喜欢
                    • 1970-01-01
                    • 2010-11-13
                    • 1970-01-01
                    • 2013-04-17
                    • 1970-01-01
                    • 2014-07-23
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多