I have a table that I am creating with CSS Grid for responsive layout. But on small screensizes the column-headers overlap even if you are using overflow-x: auto;
How could I get it to not turn on?
Code:
<div class="table container">
<table>
<thead>
<tr>
<th>Month</th>
<th>Savings</th>
<th>Savings</th>
<th>Savings</th>
<th>Savings</th>
</tr>
</thead>
<tbody style="overflow-x:auto;">
<tr>
<td>January</td>
<td>$100</td>
<td>$100</td>
<td>$100</td>
<td>$100</td>
</tr>
</tbody>
</table>
</div>
CSS:
table {
margin: 2rem 0 2rem 0;
border-collapse: collapse;
border-spacing: 0;
width: fit-content;
overflow-x: auto;
display:grid;
grid-template-columns: 100px 1fr;
thead {
tr {
display:grid;
grid-gap: 1rem;
grid-auto-flow: column;
grid-template-rows: repeat(5, .5fr);
justify-content: center;
align-items: center;
text-align: center;
font-size: .9rem;
}
}
tbody {
display:grid;
grid-template-columns: repeat(auto-fit, minmax(10px, 1fr));
tr {
display:grid;
grid-auto-flow: column;
grid-template-rows: repeat(5, 1fr);
justify-content: center;
align-items: center;
text-align: center;
font-size: .9rem;
}
}
}
Here is an image of what happens:
A CSS-grid already displays like a HTML table.
Simplifying the design by using a single grid instead of two grids nested inside a parent grid removes the problematic behaviour:
Code:
<div class="grid-table">
<div>Month</div>
<div>Savings</div>
<div>Savings</div>
<div>Savings</div>
<div>Savings</div>
<div>January</div>
<div>$100</div>
<div>$100</div>
<div>$100</div>
<div>$100</div>
</div>
CSS:
.grid-table {
margin: 2rem 0 2rem 0;
border-collapse: collapse;
border-spacing: 0;
width: fit-content;
overflow-x: auto;
display:grid;
grid-template-columns: 100px 1fr;
grid-gap: 1rem;
grid-auto-flow: column;
grid-template-rows: repeat(5, .5fr);
justify-content: center;
align-items: center;
text-align: center;
font-size: .9rem;
}