Do we really need to use div.responsive
? Here's an alternative solution.
I decided to include a <thead>
and <tbody>
to separate the header and body sections.
<thead>
and <tbody>
each have their own scroll bar. To ensure that the set width is applied to <thead>
, I used display: block
:
thead,
tbody {
display: block;
overflow-x: scroll;
width: 400px;
}
To guarantee equal cell widths, I added min-width
to all cells with a reasonable value:
th,
td {
text-align: left;
padding: 8px;
min-width: 70px;
}
To make the header sticky, I utilized position: sticky
on <thead>
and hid the scrollbar. A JavaScript snippet was included to synchronize horizontal scrolls:
thead {
overflow-x: hidden;
position: sticky;
top: 0;
}
const thead = document.querySelector('thead');
const tbody = document.querySelector('tbody');
tbody.addEventListener('scroll', () => {
thead.scrollLeft = tbody.scrollLeft;
})
table {
border-collapse: collapse;
border: 1px solid #ddd;
}
thead,
tbody {
display: block;
overflow-x: scroll;
width: 400px;
}
thead {
overflow-x: hidden;
position: sticky;
top: 0;
}
th,
td {
text-align: left;
padding: 8px;
min-width: 70px;
}
th {
background-color: #000;
color: white;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<h2>Responsive Table</h2>
<p>If you have a table that is too wide, you can add a container element with overflow-x:auto around the table, and it will display a horizontal scroll bar when needed.</p>
<p>Resize the browser window to see the effect. Try removing the div element to observe changes in the table appearance.</p>
<table>
<thead>
<!-- Header row data goes here -->
</thead>
<tbody>
<!-- Body row data goes here -->
</tbody>
</table>
</body>
</html>