Auto Elastic Table Column Widths

Testing across browsers to ensure table css works correctly. Seems IE8 this does not work so applying a script.

by jacobwsmith

HTML

<h1>Table Auto Column Width</h1>


		<table class="tablesorter" id="example">
			<thead>
				<tr>
					<th>&nbsp;</th>
					<th>Name</th>
					<th>Header3</th>
					<th>Header4</th>
					<th >Header5  with more</th>
					<th>Header6</th>
					<th>Header7</th>
					<th>Header8</th>
					<th>Header9</th>
					<th>Header10</th>
					<th>Header11</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td>1.</td>
					<td><a href="#">Some long winded name</a></td>
					<td>0</td>
					<td>1</td>
					<td>2</td>
					<td>3</td>
					<td>4</td>
					<td>5</td>
					<td>6</td>
					<td>777,777,777</td>
					<td>80</td>
				</tr>
				<tr>
					<td>2.</td>
					<td><a href="#">Some long winded name</a></td>
					<td>0</td>
					<td>Some more text describing the something about something</td>
					<td>2</td>
					<td>3</td>
					<td>4</td>
					<td>5</td>
					<td>6</td>
					<td>77</td>
					<td><input value="Go Get Something" type="button"/></td>
				</tr>
			</tbody>
			<tfoot>
				<tr>
					<td colspan="11">
						Total
					</td>
				</tr>
			</tfoot>
		</table>

CSS

h1 {
  font-size: 32px;
  font-weight: bold;
  margin: 10px 0 10px;
}    
table {
  width: 100%;
}
table, table thead th, table td{
  border: solid #cccccc 1px;
  padding: 4px;
}
table thead th, table tbody td {
  text-align: center;
}
table thead th {
  white-space: nowrap;
  width: auto;
}
table tfoot td {
  text-align: right;
  width: auto;
}
th.elastic, td.elastic, table thead th:nth-child(2), table tbody td:nth-child(2){
  text-align: left;
  width: 100%;
}

JavaScript

// document.ready
$(function() {
  // ie8 working!!! ======================
	tableAutoCellWidth('example', [1]);	
});
// =====================================================
			//	Auto table cell width. Sets the table column width to
			//	the width of the text in the header
			//	params:
			//	- id: String
			//	- exceptions: Array
			// =====================================================
			var tableAutoCellWidth = function(id, exceptions){
			
				// declare variables
				var span;
			
				// set the table to 100%
				$("#"+id).width('100%');
			
				// loop through all table heads that are found
				$("#"+id+" thead tr th").each(function(i, obj) {
					
					// add a span tag so we can measure
					span = document.createElement('span');
					$(span).html($(obj).html());
					$(obj).html(span);
				
			
					// do we have too much space
					if($(span).width() < $(obj).width() && $.inArray(i, exceptions)==-1){
			
						// set the th
						$(obj).width($(span).width());
			
						// loop through the column and set all the td
						$("#"+id+" tbody tr td:nth-child("+(i+1)+")").each(function(j, o){
							$(o).width($(span).width());
						});
			
					}
			
			
				});
			
			
			};