Html 如何强制浮动 DIV 匹配另一个浮动 DIV 的高度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/526294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 23:13:44  来源:igfitidea点击:

How might I force a floating DIV to match the height of another floating DIV?

htmlcssheight

提问by venkatachalam

My HTML code is just dividing the pages into two columns, 65%,35% respectively.

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

In the responsediv, I have variable data; in the notediv, I have fixed data. Even though the two divs have two different sets of data, I need them to display with the same height so that the background colors appear to fill a box containing both. Naturally, the problem is the responsediv, as its height varies depending on the amount of data currently being displayed within it.

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

How might I ensure that the height of the two columns are always equal?

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

回答by meandmycode

Wrap them in a containing div with the background color applied to it, and have a clearing div after the 'columns'.

将它们包装在应用了背景颜色的包含 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>


Updated to address some comments and my own thoughts:

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

This method works because its essentially a simplification of your problem, in this somewhat 'oldskool' method I put two columns in followed by an empty clearing element, the job of the clearing element is to tell the parent (with the background) this is where floating behaviour ends, this allows the parent to essentially render 0 pixels of height at the position of the clear, which will be whatever the highest priorly floating element is.

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

The reason for this is to ensure the parent element is as tall as the tallest column, the background is then set on the parent to give the appearance that both columns have the same height.

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

It should be noted that this technique is 'oldskool' because the better choice is to trigger this height calculation behaviour with something like clearfixor by simply having overflow: hidden on the parent element.

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

Whilst this works in this limited scenario, if you wish for each column to look visually different, or have a gap between them, then setting a background on the parent element won't work, there is however a trick to get this effect.

虽然这在这种有限的情况下有效,但如果您希望每列在视觉上看起来不同,或者它们之间有间隙,那么在父元素上设置背景将不起作用,但是有一个技巧来获得这种效果。

The trick is to add bottom padding to all columns, to the max amount of size you expect that could be the difference between the shortest and tallest column, if you can't work this out then pick a large figure, you then need to add a negative bottom margin of the same number.

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

You'll need overflow hidden on the parent object, but the result will be that each column will request to render this additional height suggested by the margin, but not actually request layout of that size (because the negative margin counters the calculation).

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

This will render the parent at the size of the tallest column, whilst allowing all the columns to render at their height + the size of bottom padding used, if this height is larger than the parent then the rest will simply clip off.

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

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

You can see an example of this technique on the bowers and wilkins website(see the four horizontal spotlight images the bottom of the page).

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

回答by Dyson

If you are trying to force a floating div to match another to create a column effect, this is what I do. I like it because it's simple and clean.

如果您试图强制浮动 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>

I think this makes sense. It seems to work well even with dynamic content.

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

回答by Justin Yost

Here is a jQuery pluginto set the heights of multiple divs to be the same. And below is the actual code of the plugin.

这是一个 jQuery 插件,用于将多个 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;
};

回答by Aaron Digulla

The correct solution for this problem is to use display: table-cell

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

Important: This solution doesn't need floatsince table-cellalready turns the divinto an element that lines up with the others in the same container. That also means you don't have to worry about clearing floats, overflow, background shining through and all the other nasty surprises that the floathack brings along to the party.

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

CSS:

CSS:

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

HTML:

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>

Related:

有关的:

回答by bendewey

You should wrap them in a div with no float.

您应该将它们包装在一个没有浮动的 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>

I also use the clearfix patch on here http://www.webtoolkit.info/css-clearfix.html

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

回答by Erich Richter

I can't understand why this issue gets pounded into the ground when in 30 seconds you can code a two-column table and solve the problem.

当您在 30 秒内编写一个两列表并解决问题时,我不明白为什么这个问题会被重创。

This div column height problem comes up all over a typical layout. Why resort to scripting when a plain old basic HTML tag will do it? Unless there are huge and numerous tables on a layout, I don't buy the argument that tables are significantly slower.

这个 div 列高度问题出现在一个典型的布局中。当一个普通的老式基本 HTML 标签可以做到时,为什么要诉诸脚本?除非布局上有大量的表格,否则我不相信表格明显变慢的说法。

回答by Nick Manning

Flex does this by default.

默认情况下,Flex 会执行此操作。

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

CSS:

CSS:

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

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

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

BONUS: multiple rows

奖励:多行

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

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

回答by HardlyNoticeable

This code will let you have a variable number of rows (with a variable number of DIVs on each row) and it will make all of the DIVs on each row match the height of its tallest neighbour:

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

If we assumed all the DIVs, that are floating, are inside a container with the id"divContainer", then you could use the following:

如果我们假设所有浮动的 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);

});
});

回答by Drew

You can always use a background image to do it too. I tend to vote for this option 100% of the time as the only other perfect solution is the Jquery option.

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

As with using the outer div with a background color you'll end up having to have the content in both divs reaching the same height.

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

回答by David

Having had the same sort of problem as well, requiring three divs next to each other with different content, with right-borders to 'seperate' them, the only solution that worked was a slightly modified version of the jQuery option in another answer. Remember you also need the script found here.

也有同样的问题,需要三个彼此相邻且内容不同的 div,用右边框“分隔”它们,唯一有效的解决方案是在另一个答案中对 jQuery 选项进行了稍微修改的版本。请记住,您还需要此处找到的脚本。

Below is my slightly modified version of the script, which just allows for a true min-height setting (as I needed my boxes to be at least a certain height).

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

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

It works like a charm and doesn't slow anything down :)

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