在多行中设置3个元素的高度,取最大值

我有一个所有浮动左边的div的布局,列数为3.在这些图层中是具有不同长度的文本,因此这些图层处于不同的高度,因此没有正确对齐,也看起来不太好,因为边框不匹配高度。

我可以为所有div设置一个固定的高度但这会在某些行上留下巨大的空白区域,所以我写了一些JQuery来获取所有div的最大值并将所有高度设置为该高度,以便它们正确排列。 该脚本是:

var sectionheight = new Array(); //set empty array $(".section-title").each(function () { //get all div elements var value = $(this).height(); //get div height sectionheight.push(value); //write height to array }); var newsectionheight = Math.max.apply(Math, sectionheight); //get largest value in array $('.section-title').height(newsectionheight); //set height of all elements to largest 

这样可以正常工作,但在设计中,一些行只有1行文本,所以它调整该行与使用5行文本的顶行一样大。

我想要实现的是它需要前3个div,获得最大值然后将这3个div高度设置为该值。 然后对第4到第6个div重复此操作,以此类推(因为div在3列中)

我可以用$(".section-title").eq(2)来做一个非常长篇的解决方案$(".section-title").eq(2)但是我可以想象这不是一个理想的做法。

任何建议表示赞赏

编辑一些div的示例(css在html中不可见,仅用于示例):

 
some text and a longer title than the other rows
some text
some text not as long
some text
short text
some text

尝试

 var $sections = $('.section-title'); $sections.filter(':nth-child(3n-2)').each(function () { var $this = $(this), $els = $this.nextAll(':lt(2)').addBack(); var sectionheight = new Array(); $els.each(function () { var value = $(this).height(); sectionheight.push(value); }); var newsectionheight = Math.max.apply(Math, sectionheight); $els.height(newsectionheight); }) 

演示: 小提琴

好试试这个:

 function setHeight(){ var max = -1; // this will give you maximum height of your div $(document).find('.test-div').each(function() { var h = $(this).height(); max = h > max ? h : max; }); // varible-div is the division whose height keeps changeing $(document).find('.variable-div').each(function(){ var presentHeight=$(this).parents('.test-div').height(), difference=max-presentHeight; if(difference > 0){ $(this).height($(this).height()+difference); } }); }