Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix an html column width to the max width of its content?

I am trying to format a table for an input form as follows. The table looks a bit like this:

       Name:
Time of day:

and so forth, where each of those field labels is then followed by the input field proper. My goals is to have a table with two columns, one for the field labels, the other for the input fields, such that:

  • The size of the left column is automatically determined by the longest field label, so that field labels are never wrapped around.
  • The input fields themselves extend as much to the right as possible.

I know of course that I can fix the left column to be e.g. 20em long, and the other column 100%, but this is not what I am asking -- I don't want to have to measure and then enter a fixed width like 20em; I would like the width to be automatically derived from the width of the longest item in that column. This sounds like a fairly common wish; is there a way to do it simply?

like image 952
Luca de Alfaro Avatar asked Sep 01 '11 01:09

Luca de Alfaro


1 Answers

Use the white-space: nowrap; CSS style, as in the code below. Of course, you will want to add margin or padding between the two columns so the colon (:) isn't pressed against the input box. jsFiddle example of the code below

HTML:

<table class="fullWidth">
    <tr>
        <td class="nowrap">Name:</td>
        <td><input type="text" /></td>
    </tr>
    <tr>
        <td class="nowrap">Time of Day:</td>
        <td><input type="text" /></td>
    </tr>
</table>

CSS:

.nowrap {
    white-space: nowrap;  
    width: 1px;
}

.fullWidth {
    width: 100%;
}

input {
    width: 100%;
    display: block;   
}
like image 174
Devin Burke Avatar answered Sep 18 '22 23:09

Devin Burke