简体   繁体   中英

Columns of Equal Height with JQuery

Can we put JQuery to use to create columns of equal height? If yes, how?

Thanks

Cycle through each column, and find the tallest. Then set all to that height.

var maxHeight = 0;
$(".column").each(function(){
  maxHeight = $(this).height() > maxHeight ? $(this).height() : maxHeight;
}).height(maxHeight);​

Online Demo: http://jsbin.com/afupe/2/edit

Highly recommend a chainable plugin approach. As this screams reusability.. You can make the equalHeights specific to the collection...

$.fn.equalHeights = function () {
  var max = 0;
  return this
    .each(function(){
      var height = $(this).height();
      max = height > max ? height : max;
    })
    .height(max);
};
// don't combine collections unless you want everything same height..
$('.top-menu a').equalHeight();
$('footer a').equalHeight();

You could take a step further and make height a property you take in so you could use for height or width like so...

$.fn.equalProp = function (prop) {
  var max = 0;
  return this
    .each(function(){
      var oProp = $(this)[prop]();
      max = oProp > max ? oProp : max;
    })
    [prop](max);
};

$('.top-menu a, .top-menu div').equalProp('height').equalProp('width');

I posted a similar question a few days ago and here's the piece of code that worked for me.

*** #column_left, #column_center, #column_right: are the three column divs that are supposed to have the same height. I suppose it can work with more or less number of columns.

<script type='text/javascript'
 src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'></script>

<script type='text/javascript'>
$(document).ready(function() {

    // get the heights
    l = $('#column_left').height();
    r = $('#column_right').height();
    c = $('#column_center').height();

    // get maximum heights of all columns
    h = Math.max(c, Math.max(l, r));

    // apply it
    $('#column_left').height(h);
    $('#column_right').height(h);
    $('#column_center').height(h);
    });
</script>

It was posted by user "widyakumara". I hope it helps you too.

@ktsixit you should give a class to all your columns instead of using unique IDs in this case. You can then calculate and apply the tallest height to all items at once. Even if you don't or can't use a class, you should at least use variables to store the div ID references. With the code above, you're parsing the DOM 6 times. You could at least reduce that to 3 parses by using variables.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM