Some text

Set brother div equal height (highest)

I am trying to set paired divs of the same height.

<div class="item ">
Some text
</div>
<div class="item right">
Some text
</div>
<div class="item ">
Some text<br/>Some text<br/>Some text<br/>Some text<br/>Some text
</div>
<div class="item right">
Some text<br/>Some text<br/>Some text<br/>Some text
</div>
<div class="item ">
Some text
</div>
<div class="item right">
Some text<br/>Some text<br/>Some text
</div>

CSS

.item{width: 45%;float: left;position: relative;border: 1px solid #000;clear:left;}
.item.right{float:right;clear:right;}

jQuery I am using

$('.item.right').prev().each(function() {
    leftheight = $(this).height();
    rightheight = $(this).next().height();      
    if(leftheight > rightheight){
        $(this).next().height(leftheight);
    }else{
        $(this).height(rightheight);
    }               
});

This does not work, and I cannot understand why.

I have two column layouts where divs have an output line border, so this is very obvious when they are not the same height. the "right class" will place the element to the right. I want the pairs to be the same, as they form a row. I do not want to use tables (css or otherwise), since the layout is dynamic for mobile (where they form a single column).

+4
source share
4 answers

map(), div / , Math.max , , . :

$('.item.right').each(function() {
    var $divs = $(this).add($(this).prev('.item'));
    var tallestHeight = $divs.map(function(i, el) {
        return $(el).height();
    }).get();
    $divs.height(Math.max.apply(this, tallestHeight));
});

+5

(.map() and Math.max.apply()):

, Math.max.apply() .

$(document).ready(function() {
   var heightArray = $(".item").map(function() {
        return  $(this).height();
   }).get();
   var maxHeight = Math.max.apply(Math, heightArray);
   $(".item").height(maxHeight);
});

+2

http://jsfiddle.net/nTFtn/ http://jsfiddle.net/6tU2m/

, !

, :)

$('.item.right').prev('div').each(function () {

    leftheight = $(this).height();
    alert(leftheight);
    rightheight = $(this).next().height();
    if (leftheight > rightheight) {

        $(this).next().height(leftheight);
    } else {
        $(this).height(rightheight);
    }
});
+2

, .

:

var max_height = 0;
$('.item.right').prev().each(function() {
  if($(this).height() > max_height) {
     max_height = $(this).height();
  }
});
$('.item.right').prev().each(function() {
    $(this).height(max_height);
}

So, the error is pointed to next(), because you are already on the correct element, and you are comparing with next()one ... Use instead prev()!

$('.item.right').prev().each(function() {
rightheight = $(this).height();
leftheight = $(this).prev().height();      
if(rightheight > leftheight){
    $(this).prev().height(rightheight);
}else{
    $(this).height(leftheight);
}               
});
+1
source

All Articles