Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How would you achieve this table based layout using CSS instead of HTML tables?

Tags:

html

css

I want the following layout to appear on the screen:

FieldName 1             [Field input 1]
FieldName 2 is longer   [Field input 2]
    .                         .
    .                         .
FieldName N             [Field input N]

Requirements:

  • Field names and field inputs must align on the left edges
  • Both columns must dynamically size themselves to their content
  • Must work cross-browsers

I find this layout extremely simple to do using HTML tables, but since I see a lot of CSS purists insisting that tables only be used for tabular data I figured I'd find out if there was a way to do it using CSS.

like image 425
17 of 26 Avatar asked Sep 20 '08 22:09

17 of 26


2 Answers

I wouldn't, I would use a table. This is a classic example of a tabular layout - exactly the sort of thing tables are supposed to be used for.

like image 169
Nick Johnson Avatar answered Oct 15 '22 17:10

Nick Johnson


I think most of the answers are missing the point that the original questioner wanted the columns widths to depend on the width of the content. I believe the only way to do this with pure CSS is by using 'display: table', 'display: table-row' and 'display: table-cell', but that isn't supported by IE. But I'm not sure that this property is desirable, I find that creating a wide columns because there is a single long field name makes the layout less aesthetically pleasing and harder to use. Wrapped lines are fine in my opinion, so I think the answers that I just suggested were incorrect are probably the way to go.

Robertc's example is ideal but if you really must use tables, I think you can make it a little more 'semantic' by using <th> for the field names. I'm not sure about this so please someone correct me if I'm wrong.

<table>
    <tr><th scope="row"><label for="field1">FieldName 1</label></th>
        <td><input id="field1" name="field1"></td></tr>
    <tr><th scope="row"><label for="field2">FieldName 2 is longer</label></th>
        <td><input id="field2" name="field2"></td></tr>
    <!-- ....... -->
</table>

Update: I haven't been following this closely, but IE8 apparently supports CSS tables, so some are suggesting that we should start using them. There's an article on 24 ways which contains a relevant example at the end.

like image 38
Daniel James Avatar answered Oct 15 '22 15:10

Daniel James