How to fix html column width to maximum width of its content?

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

Name: Time of day: 

etc., where each of these field labels follows the correct input rule. My goals are to have a table with two columns, one for the fields and one for the input fields, such that:

  • The size of the left column is automatically determined by the longest field label, so field labels never wrap around.
  • Input fields are maximally expanded to the right.

I know, of course, that I can fix the left column, for example. 20em long, and the other column is 100%, but this is not what I ask - I do not want to measure and then enter a fixed width, like 20em; I would like the width to be automatically inferred from the width of the longest element in this column. This seems like a fairly common desire; is there any way to make this simple?

+4
source share
1 answer

Use the white-space: nowrap; style white-space: nowrap; CSS like in the code below. Of course, you'll want to add a marker or pad between two columns so that the colon ( : not pressed on the input field. JsFiddle sample 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; } 
+6
source

All Articles