Making an HTML table column as small as possible but no smaller
I have a column with labels and corresponding text boxes, viz:
<table>
<tr>
<td>Label:</td>
<td><input type="text"></input></td>
</tr>
<tr>
<td>longer label:</td>
<td><input type="text"></input></td>
etc...
I want to ensure the first column is wide enough to al开发者_开发知识库low the text in one line, but no wider than necessary, that to allow maximum space for the input boxes (which are set to width 100%). So I don't want to set a specific percentage or explicit width, just something to say "as small as possible but no smaller."
Is there a way to do this in raw html/CSS or do I have to resort to Javascript?
(Obviously if the page is very narrow this is not achievable, but I'm not worried about really narrow browsers.)
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.
精彩评论