My Technical Notes

Thursday, 19 September 2013

Setting Width on an HTML Table and its Columns

If you have a table which has many columns and the table looks like it is wider than its container, then you must add some CSS to make it narrower and sit within its container properly.

First thing is to set the table a width, which can be either 99% or you can set it to a pixel value:


table.grid
{
   /* either set it to a pixel value */
   width: 920px;

   /* or set it to 99% */
   width: 99%;
}

The next thing you need to do is to set the max-width or width properties of the cells. IE7 (or IE with the meta-tag X-UA-Compatible set to IE=EmulateIE7) does not respect the max-value of table elements. Therefore you need to set the width property of these browsers:


table.grid td.name
{
   max-width: 130px; /* for FF and Chrome */
   *width: 130px; /* for IE7 and below */
}

The last thing that one needs to be aware of is breaking up long words - normally done as a test to see if the presence of a long word will cause the layout to mess up. We can use CSS to split up long words by using the word-wrap property:


table.grid td
{
   word-wrap: break-word;
}

This covers most things, but in one of the steps we set an explicit width property on the table cell for IE7 (or IE=EmulateIE7). The problem with this is that we have to decide on the widths of the columns when instead we would rather have the browser do this for us.

A quick way around this issue, is to use jQuery to set the width property, only if the column was too big. Therefore we do the following two steps:

  • Check if the column is too wide.
  • If it is too wide we set the width to the maximum width we allow, otherwise we leave it as is.


$(function() {
   var colWidth = $('td.name').width();
   if (colWidth > 130 /* we can set this to any value we want */) {
      $('td.name').css('width', 130);
   }
});

The above snippet can be extracted out to the following:


$.fn.setColumnMaxWidth = function(maxWidth) {
   // if it was firefox or chrome we simply do:
   // this.css('max-width', maxWidth + 'px');
   var colWidth = this.width();
   if (colWidth > maxWidth) {
      this.css('width', 130);
   }
};
$(function() {
   $('td.name').setColumnMaxWidth(130);
});

No comments: