Reputation: 13
I have a table that create dynamically tr and td.
After a bunch of td created, they lost their formatting and result "compressed" each other. How do i maintain constant width for each td created?
I tried to set td's width attribute but after couple of insertions they compressed itself.
I need it because the table can grow up, so i need a scrolling bar to navigate. And to do that I want the td had fixed width
Upvotes: 1
Views: 2142
Reputation: 3361
The comment above from @Milche Patern holds the key: table-layout: fixed
.
I created a JSFiddle to illustrate this: http://jsfiddle.net/UxkUC/
HTML
<div id="container">
<table id="my-fixed-width-table">
<tr>
<td> Cell 0 </td>
<td> Cell 1 </td>
<td> Cell 2 </td>
<td> Cell 3 </td>
<td> Cell 4 </td>
<td> Cell 5 </td>
<td> Cell 6 </td>
<td> Cell 7 </td>
<td> Cell 8 </td>
<td> Cell 9 </td>
</tr>
<tr>
<td> Cell 0 </td>
<td> Cell 1 </td>
<td> Cell 2 </td>
<td> Cell 3 </td>
<td> Cell 4 </td>
<td> Cell 5 </td>
<td> Cell 6 </td>
<td> Cell 7 </td>
<td> Cell 8 </td>
<td> Cell 9 </td>
</tr>
</table>
</div>
CSS
#container {
width: 100%;
overflow-x: auto;
}
#my-fixed-width-table {
table-layout: fixed;
width: 100%;
}
#my-fixed-width-table td {
width: 200px;
border: solid 1px black;
text-align: center;
}
Upvotes: 1
Reputation: 140
You need two things:
For the scroll bar, use the overflow attribute.
<style>
td { min-width: 150px; }
table { overflow: scroll; }
</style>
For more information about the overflow attribute: www.w3schools.com/cssref/pr_pos_overflow.asp
Upvotes: 3