How to fit an HTML table to the web browser

Home > Search > How-to
  by

Let's say you have the following HTML.

<style>
table {
  border: 1px solid black;
	}
table th {
    border: 1px solid black;
	}
	
table td {
    border: 1px solid black;
	}
</style>

<table>
	<tr>
		<th>Column1</th>
		<th>Column2</th>
		<th>Column3</th>
		<th>Column4</th>
		<th>Column5</th>
		<th>Column6</th>
		<th>Column7</th>
		<th>Column8</th>
		<th>Column9</th>
		<th>Column10</th>		
	</tr>
	<tr>
		<td>A very very very long string of data exists in this cell a very long string of data indeed</td>
		<td>A very very very long string of data exists in this cell a very long string of data indeed</td>
		<td>A very very very long string of data exists in this cell a very long string of data indeed</td>
		<td>A very very very long string of data exists in this cell a very long string of data indeed</td>
		<td>A very very very long string of data exists in this cell a very long string of data indeed</td>
		<td>A very very very long string of data exists in this cell a very long string of data indeed</td>
		<td>A very very very long string of data exists in this cell a very long string of data indeed</td>
		<td>A very very very long string of data exists in this cell a very long string of data indeed</td>
		<td>A very very very long string of data exists in this cell a very long string of data indeed</td>
		<td>A very very very long string of data exists in this cell a very long string of data indeed</td>		
	</tr>
</table>

 

Since the data consists of short strings of data with spaces between the data, the HTML table will automatically wrap the text and fit the table to the browser.

 

However, when there are long strings of data with no spaces between the data, the HTML table will not wrap the text and you will need to scroll left / right to view all of the columns of the HTML table. This is not ideal.

 

This can be resolved by adding width: 100% and table-layout: fixed to the table style, and word-wrap: break-word to the table th and td style.

<style>
table {
	border: 1px solid black;
    width: 100%;
    table-layout: fixed;	
	}
table th {
    border: 1px solid black;
	word-wrap: break-word;
	}

table td{
    border: 1px solid black;
	word-wrap: break-word;
	}
</style>

 

 

Now, even if cells have long strings of data, the text will wrap and the HTML table will fit in the browser with no need to scroll left / right.



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments