[jquery] Setting equal heights for div's with jQuery

I want to set equal height for divs with jQuery. All the divs may have different amount of content and different default height. Here is a sample of my html layout:

<div class="container">
    <div class="column">This is<br />the highest<br />column</div>
    <div class="column">One line</div>
    <div class="column">Two<br />lines</div>
</div>
<div class="container">
    <div class="column">One line</div>
    <div class="column">Two<br>lines</div>
    <div class="column">One line</div>
</div>

I'm setting the height with the next jQuery function:

$(document).ready(function(){

    var highestBox = 0;
        $('.container .column').each(function(){  
                if($(this).height() > highestBox){  
                highestBox = $(this).height();  
        }
    });    
    $('.container .column').height(highestBox);

});

This works fine but not in my case because I want all the 'columns' equal only inside one 'container'. This means that in the first container all the boxes must be as high as the first div, but in the second one they must be equal to second column.

So question is -- how should I modify my jQuery to reach this?

Thank you!

This question is related to jquery html height equals

The answer is


_x000D_
_x000D_
var currentTallest = 0,_x000D_
     currentRowStart = 0,_x000D_
     rowDivs = new Array(),_x000D_
     $el,_x000D_
     topPosition = 0;_x000D_
_x000D_
 $('.blocks').each(function() {_x000D_
_x000D_
   $el = $(this);_x000D_
   topPostion = $el.position().top;_x000D_
   _x000D_
   if (currentRowStart != topPostion) {_x000D_
_x000D_
     // we just came to a new row.  Set all the heights on the completed row_x000D_
     for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {_x000D_
       rowDivs[currentDiv].height(currentTallest);_x000D_
     }_x000D_
_x000D_
     // set the variables for the new row_x000D_
     rowDivs.length = 0; // empty the array_x000D_
     currentRowStart = topPostion;_x000D_
     currentTallest = $el.height();_x000D_
     rowDivs.push($el);_x000D_
_x000D_
   } else {_x000D_
_x000D_
     // another div on the current row.  Add it to the list and check if it's taller_x000D_
     rowDivs.push($el);_x000D_
     currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);_x000D_
_x000D_
  }_x000D_
   _x000D_
  // do the last row_x000D_
   for (currentDiv = 0 ; currentDiv < rowDivs.length ; currentDiv++) {_x000D_
     rowDivs[currentDiv].height(currentTallest);_x000D_
   }_x000D_
   _x000D_
 });?
_x000D_
$('.blocks') would be changed to use whatever CSS selector you need to equalize.
_x000D_
_x000D_
_x000D_


<div class('a')>
   <div class('.cols-to-eq')></div>
   <div class('.cols-to-eq')></div>
   <div class('.cols-to-eq')></div>
   <div class('.cols-to-eq')></div>
</div>
<div class('b')>
   <div class('.cols-to-eq')></div>
   <div class('.cols-to-eq')></div>
   <div class('.cols-to-eq')></div>
   <div class('.cols-to-eq')></div>
</div>
var a = ['.a','.b'];
a.forEach(function(value) {
    var column = 0;
    $(value).find('.cols-to-eq').each(function(){
        if($(this).height() > column){
            column = $(this).height();
        }
    });
    $(value).find('.cols-to-
    eq').attr('style','height:'+column+'px');
   });

You can write the function this way also Which helps to build your code one time just to add class name or ID at the end

function equalHeight(group) {
               tallest = 0;
               group.each(function() {
                  thisHeight = jQuery(this).height();
                  if(thisHeight > tallest) {
                     tallest = thisHeight;
                  }
               });
               group.height(tallest);
            }
            equalHeight(jQuery("Add your class"));

So, below the jquery script to set the equal height to column which Math.max will calculate the two divs height and takes the highest height either it may be left or right.

$(document).ready(function() {
var Equalheights = Math.max($(“#left”).height(), $(“#right”).height());
$(“#left”). Equalheights(d);
$(“#right”). Equalheights(d);
});
Highest height will be assigned to both left and right divs

Live Demo


This is my version of setting blocks in the same hight... For example you have a divthat contains divs with the name "col"

$('.col').parent().each(function() {
    var height = 0,
        column = $(this).find('.col');
    column.each(function() {
        if ($(this).height() > height) height = $(this).height();
    });
    column.height(height);
});

I wish i'd read this post before I (with help from Earl) created this one

setMaxHeightForTitles($column, $title) {
      var maxHeight = 0;
      $column.find($title)
      .each(function(index, title){
        var height = $(title).height();
        if  (height > maxHeight) maxHeight = height;
      })
      .each(function(index, title){
        $(title).height(maxHeight);
      });
  }

Important improvement! (I added $(this).height('auto'); before measuring height - we should reset it to auto. Then we can use this function on resize)

function equalheight () {
            $('.cont_for_height').each(function(){  

                var highestBox = 0;
                $('.column_height', this).each(function(){

                    var htmlString = $( this ).html()

                    ;


                $(this).height('auto');

                    if($(this).height() > highestBox) 
                       highestBox = $(this).height(); 
                });  

                $('.column_height',this).height(highestBox);

        });  

        }

  <script>
function equalHeight(group) {
   tallest = 0;
   group.each(function() {
      thisHeight = $(this).height();
      if(thisHeight > tallest) {
         tallest = thisHeight;
      }
   });
   group.height(tallest);
}
$(document).ready(function() {
   equalHeight($(".column"));
});
</script>

Here is what worked for me. It applies the same height to each column despite their parent div.

$(document).ready(function () {    
    var $sameHeightDivs = $('.column');
    var maxHeight = 0;
    $sameHeightDivs.each(function() {
        maxHeight = Math.max(maxHeight, $(this).outerHeight());
    });
    $sameHeightDivs.css({ height: maxHeight + 'px' });
});

Source


// Select and loop the container element of the elements you want to equalise
        $('.equal').each(function(){  

          // Cache the highest
          var highestBox = 0;

          // Select and loop the elements you want to equalise
          $('.col-lg-4', this).each(function(){

            // If this box is higher than the cached highest then store it
            if($(this).height() > highestBox) {
              highestBox = $(this).height(); 
            }

          });  

          // Set the height of all those children to whichever was highest 
          $('.col-lg-4',this).height(highestBox);

        }); 

    });

You need imagesLoaded if the container have images inside. This works for responsive too.

$(document).ready(function () { 
     equalHeight('.column');
});
$(window).resize(function(){equalHeight('.column');});

function equalHeight(columnClass){
    $('.eq-height-wrap').imagesLoaded(function(){
        $('.eq-height-wrap').each(function(){  

            var maxHeight = Math.max.apply(null, $(this).find(columnClass).map(function ()
            {
                return $(this).innerHeight();
            }).get());

            $(columnClass,this).height(maxHeight);
        });
    });
}

$(document).ready(function(){

    $('.container').each(function(){  
        var highestBox = 0;

        $(this).find('.column').each(function(){
            if($(this).height() > highestBox){  
                highestBox = $(this).height();  
            }
        })

        $(this).find('.column').height(highestBox);
    });    


});

function setEqualHeight(columns) {
  var tallestColumn = 0;

  columns.each(function(){
    var currentHeight = $(this).height();

    if(currentHeight > tallestColumn){
      tallestColumn  = currentHeight;
    }
  });

  columns.height(tallestColumn);
}

=> setEqualHeight($('.column'));

You can reach each separate container using .parent() API.

Like,

var highestBox = 0;
        $('.container .column').each(function(){  
                if($(this).parent().height() > highestBox){  
                highestBox = $(this).height();  
        }
    }); 

There is a jQuery plugin for this exact purpose: https://github.com/dubbs/equal-height

If you want to make all columns the same height, use:

$('.columns').equalHeight();

If you want to group them by their top position, eg. within each container:

$('.columns').equalHeight({ groupByTop: true });

You need this:

$('.container').each(function(){  
     var $columns = $('.column',this);
     var maxHeight = Math.max.apply(Math, $columns.map(function(){
         return $(this).height();
     }).get());
     $columns.height(maxHeight);
});

Explanation

  • The following snippet constructs an array of the heights:

    $columns.map(function(){
        return $(this).height();
    }).get()
    
  • Math.max.apply( Math, array ) finds the maximum of array items

  • $columns.height(maxHeight); sets all columns' height to maximum height.

Live demo


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to height

How to Determine the Screen Height and Width in Flutter How do I change UIView Size? Adjust UILabel height to text iFrame Height Auto (CSS) CSS height 100% percent not working What is the height of Navigation Bar in iOS 7? Relative div height How to fill 100% of remaining height? CSS div 100% height Change UITableView height dynamically

Examples related to equals

this in equals method Why do we have to override the equals() method in Java? Compare two objects with .equals() and == operator Check if bash variable equals 0 Setting equal heights for div's with jQuery Java, how to compare Strings with String Arrays How can I express that two values are not equal to eachother? How to override equals method in Java How do you say not equal to in Ruby? Getting an element from a Set