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:

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:


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:

Table_data_1 Table_data_2 Table_data_3

Some JavaScript + more CSS solve this into:

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){

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
Internet Explorer 10.0+
Firefox 1.5+
Google Chrome
Opera 9.5+
Safari 3.1+
SeaMonkey 1.0+
Netscape 9.0
Firefox 1.5+
Google Chrome / Chromium
Opera 9.5+
SeaMonkey 1.0+
Netscape 9.0