Making an HTML table column as small as possible but no smaller
As long as you don't set width for the table
,tr
or td
, td
's text will be in one line. If the space is not enough you can use td {white-space:nowrap}
. This will not allow the text to go to second line, but will show a scrollbar.
Demo (JsFiddle)
td {white-space:nowrap}
<table>
<tr>
<td>Label:</td>
<td><input type="text"></td>
</tr>
<tr>
<td>longer label:</td>
<td><input type="text"></td>
</tr>
<tr>
<td>longeeeeeeeeeest label:</td>
<td><input type="text"></td>
</tr>
</table>
Make sure to set your table's width to 100% as well. An input with 100% width will only expand to 100% of it's parent element. Since a table is not naturally 100% wide (only as wide as its content) you can end up with oddly sized inputs.
Personally, I would just find a width that works and stick with it for the label's cells. Especially if you're doing this across multiple pages so that it's stays consistent.
Since you're doing something very specific with common HTML elements, I would highly suggest giving them a CSS class to avoid breaking other things. Your table and CSS could look something like this:
<style type="text/css">
table.form{width:100%}
td.label{width:150px;white-space:nowrap;}
td input{width:100%;}
</style>
<table class="form">
<tr>
<td class="label">My label:</td>
<td><input type="text" /></td>
</tr>
</table>
The caveat to this is that the table based layout is a really bad way to go, but work with what ya know best and gets the job done.