Resources‎ > ‎

Lining Up Table Columns with jQuery

I do not profess to be a JavaScript expert, let alone jQuery. Here is my attempt in writing code that makes tables in a page have their columns lined up. Use at your own risk. I do not provide any support for this.

<script type="text/javascript">
$(function() {
  var widths = new Array;

  /* get max column widths from tables */
  $('table').each(function() {
    i = 0;
    $(this).find('thead th').each(function() {
      w = $(this).width();

      if (!widths[i]) {
        widths[i] = 0;
      }
      if (w > widths[i]) {
        widths[i] = w;
      }
      ++i;
    });
  });

  /* now that we have got the max column widths, apply them
   * to all tables so that the columns line up
   */
  $('table').each(function() {
    i = 0;
    $(this).find('thead th').each(function() {
      $(this).width(widths[i++]);
    });
  });
});
</script>