John Smith
John Smith

Reputation: 6197

Table to div: adapting width

I want to do the following with div construction:

<table border="1">
<tr>
<td>Field 1</td><td><input type="text"></td>
</tr>
<tr>
<td>Field 2 longest</td><td><input type="text"></td>
</tr>
<tr>
<td>Field 3 long</td><td><input type="text"></td>
</tr>
</table>

http://jsfiddle.net/6AvMm/

the main problem is, how to do the first column as width as the longest (field 2) ? You know, tables are only for tabulary datas - and this case is clearly a layout.

Upvotes: 2

Views: 178

Answers (4)

Praxis Ashelin
Praxis Ashelin

Reputation: 5217

This would typically be done with floats. Using display: table is usually still not advised for layouts.

<div class="column">
   <div class="row">
     <p>Your content</p>
   </div>
   <div class="row">
     <p>Your content (longest field)</p>
   </div>
</div>

<div class="column">
   <div class="row">
     <p>Your content</p>
   </div>
   <div class="row">
     <p>Your content</p>
   </div>
</div>

CSS:

.column{
    float: left;
}

Demo Fiddle

This provides a lot of flexibility as you can easily adjust the amount of rows separately in each column, or simply skip the whole "row" thought and just write your content with headings in the column divs. Example

Using this method, you will have a lot more control over margins and positioning (needed for layouts), compared to the table method.

Upvotes: 1

Alex W
Alex W

Reputation: 38193

It seems like you're trying to move away from tables because of the semantic reason that tables are not suitable for layout. Therefore, I think you will have problems with your layout in the future if you just use display: table-cell and the way that property functions is changed. I would recommend using something like the following CSS to abandon tables completely:

div.tr {
    display:block;
    border: 1px solid;
    position: relative;
    padding: 3px;
}
div.tr div.td {
    display: inline-block;
    border: 1px solid;
    padding: 3px;
}
div.tr div.td:first-child {
    min-width: 35%;
}
.table {
    width: 40%;
    padding: 3px;
    border: 1px solid;
}

http://jsfiddle.net/6AvMm/6/

Upvotes: 0

Karim AG
Karim AG

Reputation: 2193

using display:table display:table-row; AND display:table-cell;

Updated fiddle

Upvotes: 2

Anon
Anon

Reputation: 2874

HTML:

<div class="holder">
    <div class="row">
        <div class="cell">Field 1</div>
        <div class="cell"><input type="text" /></div>
    </div>
    <div class="row">
        <div class="cell">Field 2</div>
        <div class="cell"><input type="text" /></div>
    </div><div class="row">
        <div class="cell">Field 3</div>
        <div class="cell"><input type="text" /></div>
    </div>
</div>

CSS:

.holder{
    display:table;
    border:1px solid #000;
    border-width:1px 1px 0 0;
}
.row{display:table-row;}
.cell{
    display:table-cell;
    border:1px solid #000;
    border-width:0 0 1px 1px;
}

DEMO

Upvotes: 2

Related Questions