KOMPX.COM or COMPMISCELLANEA.COM   

Mobile-friendly HTML table. Variant 1

If an HTML table is having too much data and may not fit the width anymore, it gets wider than the available space and breaks page layout. One (another) of the options to help it is to add horizontal scroll to the table:

12345678910
Table_data_1 Table_data_2 Table_data_3 Table_data_4 Table_data_5 Table_data_6 Table_data_7 Table_data_8 Table_data_9 Table_data_10

HTML code:


<table>
	<tr>
		<th>1</th>
		<th>2</th>
		<th>3</th>
		<th>4</th>
		<th>5</th>
		<th>6</th>
		<th>7</th>
		<th>8</th>
		<th>9</th>
		<th>10</th>
	</tr>
	<tr>
		<td>Table_data_1</td>
		<td>Table_data_2</td>
		<td>Table_data_3</td>
		<td>Table_data_4</td>
		<td>Table_data_5</td>
		<td>Table_data_6</td>
		<td>Table_data_7</td>
		<td>Table_data_8</td>
		<td>Table_data_9</td>
		<td>Table_data_10</td>
	</tr>
</table>

CSS code:


table {display: block; overflow-x: auto;}

If table is narrower than its container

CSS property of display: block makes the table to occupy horizontally only as much space as it is needed to contain the data without shrinking. Not more, not making itself to stretch from the leftmost to the rightmost sides of the available space, even if width: 100% is added to CSS:

123
Table_data_1 Table_data_2 Table_data_3

Some JavaScript + more CSS solve this into:

123
Table_data_1 Table_data_2 Table_data_3

JavaScript / jQuery code:


jQuery(document).ready(function($) {
	function tableWidth() {
		var containerWidth = $('.example2').width();
		$('.example2 > table').each(function(i){
			if($(this).find('tbody').width() < containerWidth){
				$(this).addClass('full-width');
			}else{
				$(this).removeClass('full-width');
			}
		});
	}
	$(document).ready(tableWidth);
	$(window).on('resize',tableWidth);
});

The script gets the current computed width of a container holding a table or tables within. If the width of a table's tbody is less than the container's width, then full-width CSS class is added to the table. If the width of a table's tbody is more than or equal to the container's width, then no class is added or it gets removed if added before.

CSS code:


.full-width {width: 100%; display: table;}

The full-width class gives back to a table its native CSS property of display:table. This property forces width:100% to work and makes the table to fill all available width.

Browser support
Windows
Internet Explorer 10.0+
Firefox 1.5+
Google Chrome
Opera 9.5+
Safari 3.1+
SeaMonkey 1.0+
Netscape 9.0
Linux
Firefox 1.5+
Google Chrome / Chromium
Opera 9.5+
SeaMonkey 1.0+
Netscape 9.0
More