Reputation: 3125
There are thousands of articles about how to make a table with fixed header and scrollable body.
But I didn't find any about a table with scrollable header.
In my case there are a lot of columns and they don't have enough space on the screen, how can it be made to have a fixed width and be scrollable horizontally?
I've tried to include the table
inside a div
:
<div className="table-container">
<table> ... </table>
</div>
.table-container {
width: 50%;
}
Upvotes: 1
Views: 59
Reputation: 6696
You can use position: sticky
however, be aware that this is not supported by older browsers.
<div style="position: relative; top: 25px; left: 25px; width: 500px; height: 150px; overflow: auto;">
<table style="width: 100%;">
<thead>
<tr>
<th style="position: sticky; top: 0; background-color: silver;">Column 1</th>
<th style="position: sticky; top: 0; background-color: silver;">Column 2</th>
<th style="position: sticky; top: 0; background-color: silver;">Column 3</th>
<th style="position: sticky; top: 0; background-color: silver;">Column 4</th>
</tr>
</thead>
<tbody style="overflow: auto;">
<tr>
<td>Row 1 Col 1</td><td>Row 1 Col 2</td><td>Row 1 Col 3</td><td>Row 1 Col 4</td>
</tr>
<tr>
<td>Row 2 Col 1</td><td>Row 2 Col 2</td><td>Row 2 Col 3</td><td>Row 2 Col 4</td>
</tr>
<tr>
<td>Row 3 Col 1</td><td>Row 3 Col 2</td><td>Row 3 Col 3</td><td>Row 3 Col 4</td>
</tr>
<tr>
<td>Row 4 Col 1</td><td>Row 4 Col 2</td><td>Row 4 Col 3</td><td>Row 4 Col 4</td>
</tr>
<tr>
<td>Row 5 Col 1</td><td>Row 5 Col 2</td><td>Row 5 Col 3</td><td>Row 5 Col 4</td>
</tr>
<tr>
<td>Row 6 Col 1</td><td>Row 6 Col 2</td><td>Row 6 Col 3</td><td>Row 6 Col 4</td>
</tr>
<tr>
<td>Row 7 Col 1</td><td>Row 7 Col 2</td><td>Row 7 Col 3</td><td>Row 7 Col 4</td>
</tr>
<tr>
<td>Row 8 Col 1</td><td>Row 8 Col 2</td><td>Row 8 Col 3</td><td>Row 8 Col 4</td>
</tr>
<tr>
<td>Row 9 Col 1</td><td>Row 9 Col 2</td><td>Row 9 Col 3</td><td>Row 9 Col 4</td>
</tr>
<tr>
<td>Row 10 Col 1</td><td>Row 10 Col 2</td><td>Row 10 Col 3</td><td>Row 10 Col 4</td>
</tr>
</tbody>
</table>
</div>
Upvotes: 1
Reputation: 700
check out w3schools
.table-container {
width: 50%;
overflow-x:auto;
}
Upvotes: 1