I use Java to create an HTML file (regular text file with .html extension) with a table and also fill it at runtime. Each column should be around 300px wide max (for now) but, other than that, the text should use all the space it needs: A column with only short text, like "123", in all cells should be quite narrow, while a column with a 200 character text should span the whole 300px and wrap the text into multiple lines.
The text is passed by a different Java class that I have no control over, so I don't know in advance what text and how much of it is going to be in the table. There could be 3 columns, or 30, and it's fine if the browser's horizontal scrollbar is shown.
I'm currently experiencing problems with short text:
If it contains white space characters (like a space " "), then the column's width is decreased and the text wraps into the next line, once the table is wider than the available screen width and the horizontal scrollbar is shown. If the cell doesn't contain any white spaces, then its width doesn't change.
I know about white-space: nowrap; but with that long text bleeds into the next cell, instead of wrapping at 300px.
If I use e.g. min-width: 100px, only the text that exceeds 100px is wrapped but then columns with little to no text are also 100px wide, even though they could be using up less space.
Question:
How do I prevent short text that contains white space characters from wrapping until it hits the column's max-width mark (without overflowing/truncating)? I'm aware I could (probably) check the text's length in Java and change the cell's CSS style to either one that uses white-space: normal or another one with white-space: nowrap, once it exceeds a certain character count, but I'm interested in a solution that only uses vanilla HTML and CSS (is this even possible?).
You can change the width of the right side of the screen in this jsfiddle to see the problem.
Here's my code:
table {
border: 1px solid black;
border-collapse: collapse;
}
table td,
table th {
border: 1px solid black;
word-wrap: break-word;
white-space: normal;
/* min-width: 100px; */
max-width: 300px;
}
<table>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
</tr>
<tr>
<td>A</td>
<td>This is a long text!</td>
<td>short</td>
<td>12345678901234567890</td>
</tr>
<tr>
<td>short</td>
<td>short</td>
<td>longlonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglonglong</td>
<td>11111111111111111111</td>
</tr>
<tr>
<td>This</td>
<td>is</td>
<td>text!</td>
<td>09876543210987654321</td>
</tr>
</table>