Html 可变高度的 CSS 浮动 Div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5234749/
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-29 07:12:15  来源:igfitidea点击:

CSS Floating Divs At Variable Heights

csshtmlcss-float

提问by stevenmc

I have infinite number of divs of a 100px width, which can fit into a 250px width parent. Regardless of height, I need the divs to be displayed in rows, as shown in the image. I've tried resolving this, but the div height seems to be screwing it up.

我有无限数量的 100 像素宽度的 div,可以放入 250 像素宽度的父级。无论高度如何,我都需要按行显示 div,如图所示。我试过解决这个问题,但 div 高度似乎把它搞砸了。

enter image description here

在此处输入图片说明

I'd really appreciate your help. Thanks :)

我真的很感激你的帮助。谢谢 :)

        <style>
            #holder{
            width:250px;
            border:1px dotted blue;
            display:inline-block;
        }
        .box{
            width:100px;
            height:150px;
            background-color:#CCC;
            float:left;
            text-align:center;
            font-size:45px;
            display:inline-block;
        }
        .one{
            background-color:#0F0;
            height:200px;
        }

        .two{
            background-color:#0FF;
        }

        .three{
            background-color:#00F;
        }

        .four{
            background-color:#FF0;
        }
    </style>

    <div id="holder">
        <div class="box one">1</div>
        <div class="box two">2</div>
        <div class="box three">3</div>
        <div class="box four">4</div>
    </div>

Here is the jsfiddle

这是jsfiddle

Here is what I did and achieved using javascript https://jsfiddle.net/8o0nwft9/

这是我使用 javascript https://jsfiddle.net/8o0nwft9/所做和实现的

采纳答案by thirtydot

To my knowledge, there's no way to fix this problem with pure CSS (that works in all common browsers):

据我所知,纯 CSS 无法解决此问题(适用于所有常见浏览器):

  • Floats don't work.
  • display: inline-blockdoesn't work.
  • position: relativewith position: absoluterequires manual pixel tuning. If you're using a server-side language, and you're working with images (or something with predictable height), you can handle the pixel tuning "automatically" with server-side code.
  • 浮动不起作用
  • display: inline-block不起作用
  • position: relativeposition: absolute需要手动调谐像素。如果您使用的是服务器端语言,并且您正在处理图像(或具有可预测高度的东西),则可以使用服务器端代码“自动”处理像素调整。

Instead, use jQuery Masonry.

相反,使用jQuery Masonry

回答by FatherStorm

on the assumption that your needs are more like your colored example code then:

假设您的需求更像您的彩色示例代码,那么:

.box:nth-child(odd){
    clear:both;
}

if it's going to be 3 rows then nth-child(3n+1)

如果它将是 3 行,那么 nth-child(3n+1)

回答by Yandy_Viera

I'm providing this answer because even when there are good ones which do provide a solution(using Masonry) still isn't crystal clear why it isn't possible to achieve this by using floats.

我提供这个答案是因为即使有很好的解决方案(使用 Masonry)仍然不清楚为什么不能通过使用浮点数来实现这一点。

(this is important - #1).

(这很重要 - #1)。

A floated element will move as far to the left or right as it can in the position where it was originally

浮动元素将尽可能向左或向右移动到原来的位置

So put it in this way:

所以这样说吧:

We have 2 div

我们有 2 个 div

<div class="div5">div5</div>
<div class="div6">div6</div>

.div-blue{
    width:100px;
    height:100px;
    background: blue;
}

.div-red{
    width:50px;
    height:50px;
    background: red;
}

without floatthey'll be one below the other

没有float他们将是一个低于另一个

enter image description here

在此处输入图片说明

If we float: rightthe div5, the div6is positioned on the line where the div5was ,

如果我们float: rightdiv5,在div6定位上线的地方div5是,

/*the lines are just for illustrate*/

/*the lines are just for illustrate*/

enter image description here

在此处输入图片说明

So if now we float: leftthe div6it will move as far to the left as it can, "in this line" (see #1 above), so if div5changes its line, div6will follow it.

因此,如果现在我们float: leftdiv6它尽可能向左移动,“在此行中”(参见上面的#1),因此如果div5更改其行,div6将跟随它。

Now let's add other div into the equation

现在让我们将其他 div 添加到等式中

<div class="div4">div4</div>
<div class="div5">div5</div>
<div class="div6">div6</div>

.div-gree{
    width:150px;
    height:150px;
    background: green;

    float:right;
}

We have this

我们有这个

enter image description here

在此处输入图片说明

If we set clear: rightto the div5, we are forcing it to take the line bellow div4

如果我们设置clear: rightdiv5,我们将强制它采取下面的行div4

enter image description here

在此处输入图片说明

and div6will float in this new line wether to the right or to the left.

并将div6在这个新行中向右或向左浮动。

Now lets use as example the question that brought me here due to a duplicate Forcing div stack from left to right

现在让我们以问题为例,由于从左到右重复强制 div 堆栈而将我带到这里

Here the snippet to test it:

这里是测试它的片段:

div{
    width:24%;
    margin-right: 1%;
    float: left;
    margin-top:5px;
    color: #fff;
    font-size: 24px;
    text-align: center;
}

.one{
    background-color:red;
    height: 50px;
}

.two{
    background-color:green;
    height:40px;
}

.three{
    background-color:orange;
    height:55px;
}

.four{
    background-color:magenta;
    height:25px;
}

.five{
    background-color:black;
    height:55px;
}
<div class="one">1</div>
<div class="two">2</div>
<div class="three">3</div>
<div class="four">4</div>
<div class="five">5</div>

<div class="one">1*</div>
<div class="three">2*</div>
<div class="four">3*</div>
<div class="two">4*</div>
<div class="five">5*</div>

enter image description here

在此处输入图片说明

In the above image you can see how div.5is stocked just next to div.3that is because in its line (defined by the line box of div.4) that is as far it can go, div.1*, div.2*, etc, also float left of div.5but as they don't fit in that line they go to the line bellow (defined by the line box of div.5)

在上面的图片中,您可以看到div.5它旁边的库存情况div.3是因为在它的行(由 的行框定义div.4)中,它可以走的最远div.1*div.2*, 等也向左浮动,div.5但因为它们不适合在该行中,他们转到下面的行(由 的行框定义div.5

Now notice that when we reduce the height of div.2*enough to be less than div.4*how it let pass to div.5*:

现在请注意,当我们将div.2*足够的高度减小到小于div.4*它如何传递给时div.5*

enter image description here

在此处输入图片说明

I hope this helps to clarify why this can not be achieved using floats. I only clarify using floats (not inline-block) because of the title "CSS Floating Divs At Variable Heights" and because right now the answer is quite long.

我希望这有助于澄清为什么使用浮点数无法实现这一点。由于标题“ CSS Floating Divs At Variable Heights”,我只澄清使用浮动(而不是内联块),因为现在答案很长。

回答by stevenmc

As has been rightly pointed out, this is impossible with CSS alone... thankfully, I've now found a solution in http://isotope.metafizzy.co/

正如已经正确指出的那样,仅靠 CSS 是不可能的……谢天谢地,我现在在http://isotope.metafizzy.co/找到了解决方案

It seems to solve the problem fully.

它似乎完全解决了问题。

回答by stevenmc

With a little help from this comment (CSS Block float left) I figured out the answer.

在此评论(CSS Block float left)的帮助下,我找到了答案。

On every "row" that I make, I add a class name left.
On every other "row" that I make, I add a class name right.

在我制作的每一“行”上,我添加了一个类名left
在我创建的每隔一个“行”上,我添加一个类名right

Then I float left and float right for each of these class names!

然后我为这些类名中的每一个向左浮动和向右浮动!

The only complication is that my content order is reversed on the "right" rows, but that can be resolved using PHP.

唯一的复杂之处是我的内容顺序在“正确”行上颠倒了,但这可以使用 PHP 解决。

Thanks for your help folks!

谢谢大家的帮助!

#holder{
  width:200px;
  border:1px dotted blue;
  display:inline-block;
}
.box{
  width:100px;
  height:150px;
  background-color:#CCC;
  float:left;
  text-align:center;
  font-size:45px;
}
.one{
  background-color:#0F0;
  height:200px;
}

.two{
  background-color:#0FF;
}

.three{
  background-color:#00F;
  float:right;
}

.four{
  background-color:#FF0;
  float:right;
}
.left{float:left;}
.right{float:right;}
<div id="holder">
  <div class="box one left">1</div>
  <div class="box two left">2</div>
  <div class="box four right">4</div>
  <div class="box three right">3</div>
</div>
</body>

回答by stevenmc

Thanks to thirtydot, I have realised my previous answer did not properly resolve the problem. Here is my second attempt, which utilizes JQuery as a CSS only solution appears impossible:

多亏了三十点,我意识到我之前的回答没有正确解决问题。这是我的第二次尝试,它使用 JQuery 作为 CSS 唯一的解决方案似乎是不可能的:

<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
        <script type="text/javascript" language="javascript">
            $(document).ready(function() {
                var numberOfColumns = 3;
                var numberOfColumnsPlusOne = numberOfColumns+1;
                var marginBottom = 10;  //Top and bottom margins added
                var kids = $('#holder:first-child').children();
                var add;
                $.each(kids, function(key, value) {
                    add = numberOfColumnsPlusOne+key;
                    if (add <= kids.length){
                        $('#holder:first-child :nth-child('+(numberOfColumnsPlusOne+key)+')').offset({ top: $('#holder:first-child :nth-child('+(key+1)+')').offset().top+$('#holder:first-child :nth-child('+(key+1)+')').height()+marginBottom });
                    }
                });
            });             
        </script>
        <style>
            #holder{
                width:270px;
                border:1px dotted blue;
                display:inline-block; /* Enables the holder to hold floated elements (look at dotted blue line with and without */
            }
            .box{
                width:80px;
                height:150px;
                background-color:#CCC;
                margin:5px;
                text-align:center;
                font-size:45px;
            }
            .one{
                height:86px;
            }
            .two{
                height:130px;
            }
            .three{
                height:60px;
            }
            .four{
                clear:both;
                height:107px;
            }
            .five{
                height:89px;
            }
            .six{
                height:89px;
            }
            .left{float:left;}
            .right{float:right;}
        </style>
    </head>
    <body>      
        <div id="holder">
            <div class="box one left">1</div>
            <div class="box two left">2</div>
            <div class="box three left">3</div>
            <div class="box four left">4</div>
            <div class="box five left">5</div>
            <div class="box six left">6</div>
        </div>
    </body>
</body>

The only problem that remains for my solution is, what happens when a box is two-box-widths instead of just one. I'm still working on this solution. I'll post when complete.

我的解决方案剩下的唯一问题是,当一个盒子是两个盒子宽度而不是一个盒子时会发生什么。我仍在研究这个解决方案。我会在完成后发布。

回答by rodiwa

If any one is still looking for alternatives, here's one. Try using the (-moz-/-webkit-) column-width property. It takes care of the variable div height issue. However column-width adds new div at the end of column.

如果有人仍在寻找替代品,这里有一个。尝试使用 (-moz-/-webkit-) column-width 属性。它负责处理可变 div 高度问题。但是 column-width 在列的末尾添加了新的 div。

Else, jQuery Masonry works best.

否则,jQuery Masonry 效果最好。

回答by bolvo

This may not be the exact solution for everybody but I find that (quite literally) thinking outside the box works for many cases: in stead of displaying the the boxes from left to right, in many cases you can fill the left column first, than go to the middle, fill that with boxes and finally fill the right column with boxes. Your image would then be:

这可能不是每个人的确切解决方案,但我发现(实际上)跳出框框思考适用于许多情况:不是从左到右显示框,在许多情况下,您可以先填充左列,而不是去中间,用盒子填充,最后用盒子填充右列。您的图像将是:

order of filling :

填写顺序

If you are using a scripting language like php you can also fill the columns from left to right by adding a new box to it and outputting when all columns are filled. eg (untested php code):

如果您使用像 php 这样的脚本语言,您还可以通过向其中添加一个新框并在所有列都填满时输出来从左到右填充列。例如(未经测试的 php 代码):

$col1 = '<div class="col1"> <div>box1</div>';
$col2 = '<div class="col2"> <div>box2</div>';
$col3 = '<div class="col3"> <div>box3</div>';
$col1 .= '<div>box4</div> </div>'; //last </div> closes the col1 div
$col2 .= '<div>box5</div> </div>';
$col3 .= '<div>box6</div> </div>';
echo $col1.$col2.$col3;

$col1, $col2 and $col3 can have float:left and width: 33%, set the boxes inside the div to full width and no float.

$col1、$col2 和 $col3 可以有 float:left 和 width: 33%,将 div 内的框设置为全宽且无浮动。

Obviously if you are using javascript / jquery to load the boxes dynamically you are better of styling them this way as well, as explained in other answers to this thread.

显然,如果您使用 javascript / jquery 动态加载框,您最好也以这种方式设置它们的样式,如该线程的其他答案中所述。

回答by Shahid Amin

to display just put this css to your div and then you have the desired layout. no need of any plug in or JS.

显示只需将此 css 放入您的 div 中,然后您就拥有所需的布局。不需要任何插件或 JS。

 .Your_Outer {
    background-color: #FFF;
    border: 1px solid #aaaaaa;
    float: none;
    display:inline-block;
    vertical-align:top;
    margin-left: 5px;
    margin-bottom: 5px;
    min-width: 152.5px;
    max-width: 152.5px;
}

you can edit the code as per your requirements :)

您可以根据您的要求编辑代码:)

回答by Flavio Tordini

On modern browsers you can simply do:

在现代浏览器上,您可以简单地执行以下操作:

display: inline-block;
vertical-align: top;