Bootstrap FreeKB - HTML - Fit a table to the web browser (word-wrap break-word)
HTML - Fit a table to the web browser (word-wrap break-word)

Updated:   |  HTML articles

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: auto or 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: auto;	
	}
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.




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


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