【问题标题】:How might I force a floating DIV to match the height of another floating DIV?如何强制浮动 DIV 匹配另一个浮动 DIV 的高度?
【发布时间】:2010-10-06 07:01:47
【问题描述】:

我的 HTML 代码只是将页面分成两列,分别为 65% 和 35%。

<div style="float : left; width :65%; height:auto;background-color:#FDD017;">
   <div id="response">
   </div> 
</div>
<div style="float : left; width :35%;height:auto; background-color:#FDD017;">
   <div id="note">
   </div>
</div> 

responsediv中,我有可变数据;在notediv,我有固定数据。 即使两个divs 有两组不同的数据,我需要它们以相同的高度显示,以便背景颜色看起来填充包含两者的框。当然,问题出在responsediv,因为它的高度取决于当前显示在其中的数据量。

如何确保两列的高度始终相等?

【问题讨论】:

    标签: html css height


    【解决方案1】:

    Flex 默认会这样做。

    <div id="flex">
     <div id="response">
     </div> 
     <div id="note">
     </div>
    </div>   
    

    CSS:

    #flex{display:flex}
    #response{width:65%}
    #note{width:35%}
    

    https://jsfiddle.net/784pnojq/1/

    奖励:多行

    https://jsfiddle.net/784pnojq/2/

    【讨论】:

      【解决方案2】:

      这个问题的正确解决方法是使用display: table-cell

      重要提示:此解决方案不需要float,因为table-cell 已经将div 转换为与同一容器中的其他元素对齐的元素。这也意味着您不必担心清除浮动、溢出、背景闪烁以及float hack 带来的所有其他令人讨厌的惊喜。

      CSS:

      .container {
        display: table;
      }
      .column {
        display: table-cell;
        width: 100px;
      }
      

      HTML:

      <div class="container">
          <div class="column">Column 1.</div>
          <div class="column">Column 2 is a bit longer.</div>
          <div class="column">Column 3 is longer with lots of text in it.</div>
      </div>
      

      相关:

      【讨论】:

        【解决方案3】:

        如果您试图强制浮动 div 匹配另一个以创建列效果,这就是我所做的。我喜欢它,因为它简单干净。

        <div style="background-color: #CCC; width:300px; overflow:hidden; ">
            <!-- Padding-Bottom is equal to 100% of the container's size, Margin-bottom hides everything beyond
                 the container equal to the container size. This allows the column to grow with the largest
                 column. -->
            <div style="float: left;width: 100px; background:yellow; padding-bottom:100%; margin-bottom:-100%;">column a</div>
            <div style="float: left;width: 100px;  background:#09F;">column b<br />Line 2<br />Line 3<br />Line 4<br />Line 5</div>
            <div style="float:left; width:100px; background: yellow; padding-bottom:100%; margin-bottom:-100%;">Column C</div>
            <div style="clear: both;"></div>
        </div>
        

        我认为这是有道理的。即使是动态内容,它似乎也能很好地工作。

        【讨论】:

        • 是的..100% 听起来比一个非常高的固定数字要好得多..谢谢
        • 唯一的问题是我希望每列都有一个边框,这将隐藏底部边框。 :(
        • +1 表示一种有趣的技术。经过一些实验,我注意到填充的百分比值实际上是基于元素的宽度,因此高于 100% 可能是个好主意(对于纵向视图)。见mdn
        • 这项技术真正伟大的方面之一是它似乎与 Foundation 等 CSS 框架高度兼容。此外,它不会影响在移动视图中压缩为单列的矩阵。总而言之,我认为这是#1 解决方案。
        • 一件事...代替
          您可以在父级后添加 :after。这将删除无意义的标记
        【解决方案4】:

        当您在 30 秒内编写一个包含两列的表格并解决问题时,我不明白为什么这个问题会被搁置一旁。

        这个 div 列高问题出现在一个典型的布局中。当一个普通的旧基本 HTML 标记可以做到这一点时,为什么还要求助于脚本呢?除非布局上有大量的表格,否则我不相信表格明显慢的说法。

        【讨论】:

        • 大多数客户都知道“基于 div 的布局”是热门事物,他们告诉我们不要使用表格。遇到过很多客户想要在所有设计布局中使用 0 个表格。
        • 表格用于表格。 CSS 用于布局。操作问题很简单,但解决方案应该扩展到任何复杂性。如果我有 16 列布局怎么办?我可以使用 16 列的表格,但是当我想更改网站样式时怎么办?我有一个乱七八糟的代码。
        【解决方案5】:

        也遇到过同样的问题,需要三个相邻的具有不同内容的 div,用右边框将它们“分开”,唯一有效的解决方案是另一个 jQuery 选项的略微修改版本回答。请记住,您还需要找到 here 的脚本。

        下面是我稍微修改过的脚本版本,它只允许设置真正的最小高度(因为我需要我的盒子至少有一定的高度)。

        /*--------------------------------------------------------------------
         * JQuery Plugin: "EqualHeights"
         * by:    Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com)
         *
         * Copyright (c) 2008 Filament Group
         * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
         *
         * Description:   Compares the heights or widths of the top-level children of a provided element
                          and sets their min-height to the tallest height (or width to widest width). Sets in em units
                          by default if pxToEm() method is available.
         * Dependencies: jQuery library, pxToEm method    (article:
                          http://www.filamentgroup.com/lab/retaining_scalable_interfaces_with_pixel_to_em_conversion/)
         * Usage Example: $(element).equalHeights();
                          Optional: to set min-height in px, pass a true argument: $(element).equalHeights(true);
                          Optional: to specify an actual min-height (in px), pass an integer value, regardless of previous parameter: $(element).equalHeights(false,150);
         * Version: 2.0, 08.01.2008
        --------------------------------------------------------------------*/
        
        $.fn.equalHeights = function(px,minheightval) {
            $(this).each(function(){
                if (minheightval != undefined) { 
                    var currentTallest = minheightval;    
                } 
                else { 
                    var currentTallest = 0;
                }
                $(this).children().each(function(i){
                    if ($(this).height() > currentTallest) { 
                        currentTallest = $(this).height();
                    }
                });
                if (!px || !Number.prototype.pxToEm) 
                    currentTallest = currentTallest.pxToEm(); //Use ems unless px is specified.
                // For Internet Explorer 6, set height since min-height isn't supported.
                if ($.browser.msie && $.browser.version == 6.0) { 
                    $(this).children().css({'height': currentTallest});
                }
                $(this).children().css({'min-height': currentTallest});
            });
            return this;
        };
        

        它就像一个魅力,不会减慢任何速度:)

        【讨论】:

        • 读者对这个脚本要非常小心,如果你包含这个插件,它就会被许可为 GPL v2。在您的应用程序中嵌入 GPL v2 javascript 被普遍接受意味着您必须开源您的整个网站
        【解决方案6】:

        将它们包装在一个包含背景颜色的 div 中,并在“列”之后有一个清除 div。

        <div style="background-color: yellow;">
          <div style="float: left;width: 65%;">column a</div>
          <div style="float: right;width: 35%;">column b</div>
          <div style="clear: both;"></div>
        </div>
        

        更新以解决一些 cmets 和我自己的想法:

        这种方法之所以有效,是因为它本质上是对您的问题的简化,在这个有点“oldskool”的方法中,我将两列放在后面跟着一个空的清除元素,清除元素的工作是告诉父级(有背景)这是浮动行为结束的地方,这允许父级在 clear 位置基本上渲染 0 像素的高度,这将是任何最高的先前浮动元素。

        这样做的原因是为了确保父元素与最高的列一样高,然后在父元素上设置背景以使两列具有相同的高度。

        应该注意的是,这种技术是“oldskool”,因为更好的选择是使用 clearfix 之类的东西来触发这种高度计算行为,或者只是在父元素上设置 overflow: hidden。

        虽然这在这种有限的场景中有效,但如果您希望每列看起来不同,或者它们之间有间隙,那么在父元素上设置背景将不起作用,但是有一个技巧可以做到这一点效果。

        诀窍是为所有列添加底部填充,达到您期望的最大大小,这可能是最短和最高列之间的差异,如果您无法解决这个问题,请选择一个大数字,然后需要添加相同数字的负下边距。

        您需要在父对象上隐藏溢出,但结果将是每列将请求呈现由边距建议的额外高度,但实际上并未请求该尺寸的布局(因为负边距会抵消计算)。

        这将以最高列的大小呈现父级,同时允许所有列以它们的高度 + 使用的底部填充的大小呈现,如果此高度大于父级,则其余列将简单地剪掉。

        <div style="overflow: hidden;">
          <div style="background: blue;float: left;width: 65%;padding-bottom: 500px;margin-bottom: -500px;">column a<br />column a</div>
          <div style="background: red;float: right;width: 35%;padding-bottom: 500px;margin-bottom: -500px;">column b</div>
        </div>
        

        您可以在bowers and wilkins website 上查看此技术的示例(请参阅页面底部的四个水平聚光灯图像)。

        【讨论】:

        • 如果两列具有不同的背景颜色将无济于事。
        • 他的例子没有这个要求,不过谢谢你的反对:)。
        • 我知道这真的很老了,但无论如何 +1。你能解释一下为什么会这样吗?
        • 在我正在做的一个项目中完美地为我工作。谢谢。 +1
        • 你会推荐使用margin-padding hack还是将内容放入同一行的td标签?
        【解决方案7】:

        此代码将使您拥有可变数量的行(每行上具有可变数量的 DIV),并且它将使每行上的所有 DIV 与其最高邻居的高度匹配:

        如果我们假设所有浮动的 DIV 都位于具有 id "divContainer" 的容器内,那么您可以使用以下内容:

        $(document).ready(function() {
        
        var currentTallest = 0;
        var currentRowStart = 0;
        var rowDivs = new Array();
        
        $('div#divContainer div').each(function(index) {
        
            if(currentRowStart != $(this).position().top) {
        
                // we just came to a new row.  Set all the heights on the completed row
                for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);
        
                // set the variables for the new row
                rowDivs.length = 0; // empty the array
                currentRowStart = $(this).position().top;
                currentTallest = $(this).height();
                rowDivs.push($(this));
        
            } else {
        
                // another div on the current row.  Add it to the list and check if it's taller
                rowDivs.push($(this));
                currentTallest = (currentTallest < $(this).height()) ? ($(this).height()) : (currentTallest);
        
            }
            // do the last row
            for(currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) rowDivs[currentDiv].height(currentTallest);
        
        });
        });
        

        【讨论】:

          【解决方案8】:

          您也可以随时使用背景图片来执行此操作。我倾向于 100% 地投票支持这个选项,因为唯一的完美解决方案是 Jquery 选项。

          与使用带有背景颜色的外部 div 一样,您最终必须让两个 div 中的内容达到相同的高度。

          【讨论】:

            【解决方案9】:

            Here is a jQuery plugin 设置多个div的高度相同。下面是插件的实际代码。

            $.fn.equalHeights = function(px) {
            $(this).each(function(){
            var currentTallest = 0;
            $(this).children().each(function(i){
                if ($(this).height() > currentTallest) { currentTallest = $(this).height(); }
                    });
                if (!px || !Number.prototype.pxToEm) currentTallest = currentTallest.pxToEm(); //use ems unless px is specified
                    // for ie6, set height since min-height isn't supported
                if ($.browser.msie && $.browser.version == 6.0) { $(this).children().css({'height': currentTallest}); }
                    $(this).children().css({'min-height': currentTallest}); 
                });
                return this;
            };
            

            【讨论】:

            • 根据设计,使用像这样的 javascript 可能是唯一的选择。
            • 纯 CSS 解决方案很少起作用,因为它们适用于简单的设计。我通常使用这样的脚本。但是在处理 AJAX 时应该小心。
            • +1 和@JohanKronberg +1 我刚刚遇到了其中一个,谢谢。
            • if (!px &amp;&amp; Number.prototype.pxToEm) 修复它以防您遇到与我相同的问题。
            • @akshar-prabhu-desai AJAX?!?,请指出这个答案中异步 JavaScript 的位置。
            【解决方案10】:

            您应该将它们包装在一个没有浮动的 div 中。

            <div style="float:none;background:#FDD017;" class="clearfix">
                <div id="response" style="float:left; width:65%;">Response with two lines</div>
                <div id="note" style="float:left; width:35%;">single line note</div>
            </div>
            

            我也在这里使用了 clearfix 补丁 http://www.webtoolkit.info/css-clearfix.html

            【讨论】:

            • 如果两列具有不同的背景颜色将无济于事。除非您知道其中一列总是比另一列长:为“包装器”赋予最短列的背景颜色,并让最长的列有自己的背景,以“伪造”两个同样长的列。
            • @Arve Systad 同意,看起来这不是 OP 想要的。
            • 如果我想为每个 div 使用两种不同的颜色怎么办?
            【解决方案11】:

            我建议您将它们都包装在具有所需背景颜色的外部 div 中。

            【讨论】:

              猜你喜欢
              • 2013-05-01
              • 2010-11-17
              • 1970-01-01
              • 2010-12-02
              • 1970-01-01
              • 1970-01-01
              • 2013-10-06
              • 2013-06-27
              • 2023-03-08
              相关资源
              最近更新 更多