许多浮动DIV的高度相同

fri*_*man 3 html css height dynamic

我有这样的情况:http://jsfiddle.net/HKHS3/ 问题是如何让div一行一行显示一行中的所有divs具有相同的高度,具体取决于最高的实际内容?

因此,根据body宽度,div一行中s 的数量会有所不同,但每次 div在行结束后的右边应该有明显的浮动并开始一个新行.

mus*_*fan 8

每行固定数量

您可以通过创建包含内部元素的row类型div来完成此操作div.

首先,您需要重构HTML,如下所示:

<div class="row">
    <div>abc</div>
    <div>adb djhf kdfhv fkjsh vhf jhds fjhf jh fjhf jh fdjh dh</div>
    <div>dhfjgh jfh gkjhfde jghf jgh jfdh gjfhd gjfdhg jfhd gjdhf jhg djhg jdh gjhfd</div>
</div>
Run Code Online (Sandbox Code Playgroud)

(你可以根据需要添加更多这样的行)

然后以下css应该做你需要的:

.row {
    display:table-row;
}

.row > div {
    width: 100px;
    display:inline-block;
    vertical-align:top;
    border: 1px solid black;
    margin: 5px;
    height:100%;
}
Run Code Online (Sandbox Code Playgroud)

这是您更新的示例


每行动态数(不完美)

上述方法的问题在于它要求div每行具有固定数量的元素.如果你想要它是动态的并且包装那么你就会遇到一个问题,只用CSS就可以了.你可以得到的最接近的如下:

div {
    width: 100px;
    display:inline-block;
    vertical-align:top;
    margin: 5px;
}
Run Code Online (Sandbox Code Playgroud)

但是元素并不都具有相同的高度,只是你不能说没有边框.由于这个原因,添加border,background-color或任何其他样式,显示元素的高度将打破效果.

这是一个例子


完全按要求(需要javascript)

值得一提的是,使用javascript可以实现你想要的效果.我不会包含这样的示例,因为实际实现将在很大程度上取决于您的真实HTML的设置方式.

实际上,我快速使用了javascript方法,但它使用了JQuery,并且可能也会进行优化:

function updateHeights() {
    var maxHeight = 0, lastY = 0, rowDivs = [], allDivs = $("div"), count = allDivs.length;

    allDivs.each(function (i) {
        var div = $(this), offset = div.offset(), y = offset.top, x = offset.left, h = div.height();

        if (h > maxHeight) maxHeight = h;//store the highest value for this row so far
        if (lastY == 0) lastY = y;//get the y position if this is the first element

        //if new row
        if (y > lastY) {
            resizeElements(rowDivs, maxHeight);//resize all elements on this row
            rowDivs.length = 0;//reset the array of row elements, ready for next row
            maxHeight = h;//set maxHeight to first of new row
        }

        lastY = y;//store current y posible for checking if we have a new row or not
        rowDivs.push(div);//add current element to row collection

        //check if last item, is so then resize this last row
        if(count - 1 == i)
            resizeElements(rowDivs, maxHeight);
    });
}

function resizeElements(elements, height) {
    for (var i = 0; i < elements.length; i++) {
        $(elements[i]).height(height);
    }
}

$(window).resize(function () {
    updateHeights();
});
updateHeights();
Run Code Online (Sandbox Code Playgroud)

这是一个有效的例子

  • @friedman:我相信你会的,但简单的事实是CSS有局限性,而你想要做的就是其中之一 (2认同)