I have a table placed within a div. The table goes beyond the width of the div. And the div has overflow-x
set to scroll. Below code works alright
body {
margin: 0;
}
.table-section {
width: 100%;
overflow-x: scroll;
padding: 10px;
background-color: lightblue;
}
.table-section table {
background-color: royalblue;
}
.table-section table th {
min-width: 150px;
}
<div class="table-section">
<table>
<thead>
<tr>
<th>
Col 1
</th>
<th>
Col 2
</th>
<th>
Col 3
</th>
<th>
Col 4
</th>
<th>
Col 5
</th>
<th>
Col 6
</th>
<th>
Col 7
</th>
<th>
Col 8
</th>
</thead>
</table>
</div>
However, if I place the whole thing within a grid cell, the overflow-x
does not seem to work. And the document body has the scroll. Code below:
body {
margin: 0;
}
.grid {
display: grid;
grid-template-columns: 230px 1fr;
}
.table-section {
grid-column: 2 / 3;
width: 100%;
overflow-x: scroll;
padding: 10px;
background-color: lightblue;
}
.table-section table {
background-color: royalblue;
}
.table-section table th {
min-width: 150px;
}
<div class="grid">
<div class="table-section">
<table>
<thead>
<tr>
<th>
Col 1
</th>
<th>
Col 2
</th>
<th>
Col 3
</th>
<th>
Col 4
</th>
<th>
Col 5
</th>
<th>
Col 6
</th>
<th>
Col 7
</th>
<th>
Col 8
</th>
</thead>
</table>
</div>
</div>
Why is it not working within a grid-cell? And how do I fix it? Thanks.
I wouldn't normally mix tables with grids. Anyway, note that in Firefox 66 overflow works fine, while in Chrome it doesn't. Remove width: 100%
from table-section
and it works fine without it in both:
See demo below:
body {
margin: 0;
}
.grid {
display: grid;
grid-template-columns: 230px 1fr;
}
.table-section {
grid-column: 2 / 3;
/*width: 100%;*/
overflow-x: scroll;
padding: 10px;
background-color: lightblue;
}
.table-section table {
background-color: royalblue;
}
.table-section table th {
min-width: 150px;
}
<div class="grid">
<div class="table-section">
<table>
<thead>
<tr>
<th>
Col 1
</th>
<th>
Col 2
</th>
<th>
Col 3
</th>
<th>
Col 4
</th>
<th>
Col 5
</th>
<th>
Col 6
</th>
<th>
Col 7
</th>
<th>
Col 8
</th>
</thead>
</table>
</div>
</div>
If your table is smaller than the grid cell - to fix, you can consider min-width: 100%
and box-sizing: border-box
to account for the padding
in the width calculations:
body {
margin: 0;
}
.grid {
display: grid;
grid-template-columns: 230px 1fr;
}
.table-section {
grid-column: 2 / 3;
min-width: 100%; /* changed */
overflow-x: scroll;
padding: 10px;
background-color: lightblue;
box-sizing: border-box; /* added */
}
.table-section table {
background-color: royalblue;
}
.table-section table th {
min-width: 150px;
}
<div class="grid">
<div class="table-section">
<table>
<thead>
<tr>
<th>
Col 1
</th>
<th>
Col 2
</th>
<th>
Col 3
</th>
<th>
Col 4
</th>
<th>
Col 5
</th>
<th>
Col 6
</th>
<th>
Col 7
</th>
<th>
Col 8
</th>
</thead>
</table>
</div>
</div>