Master Scrollable Tables with Fixed Headers: A Guide for Beginners (HTML, CSS, & JavaScript)
Making a Scrollable Table with Fixed Header (HTML, CSS, and JavaScript)Understanding the Code Components:
- HTML: We'll use standard HTML table elements (
<table>
,<thead>
,<tbody>
,<tr>
, and<th>/<td>
) to define the table structure. - CSS: We'll style the table using CSS to control the layout, scrolling behavior, and appearance.
- JavaScript (Optional): While not strictly necessary, JavaScript can be used for dynamic adjustments or complex interactions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table with Fixed Header</title>
<style>
table {
width: 100%; /* Adjust width as needed */
border-collapse: collapse;
}
thead {
position: sticky;
top: 0;
background-color: #f1f1f1; /* Optional: Set background color */
}
th, td {
padding: 10px;
border: 1px solid #ddd;
}
tbody {
height: 200px; /* Set desired scrollable height */
overflow-y: scroll;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody>
<tr>
<td>foo</td>
<td>30</td>
<td>New York</td>
</tr>
</tbody>
</table>
</body>
</html>
Explanation:
- HTML Structure: We define the table with its header (
<thead>
) and body (<tbody>
). - CSS Styling:
- We set the table width and enable collapsing borders for cleaner layout.
- The
thead
element is assigned theposition: sticky; top: 0;
properties. This makes the header "stick" to the top of the viewport when scrolling. - We style the
th
andtd
elements for padding and borders. - The
tbody
element has a set height andoverflow-y: scroll;
applied, enabling vertical scrolling within the body while keeping the header fixed.
- Content Overflowing Header: If the header content is wider than the table, it might overlap with the body. You can adjust the
width
property ofth
elements or setoverflow-x: auto;
on thethead
to enable horizontal scrolling within the header. - Uneven Column Widths: Ensure consistent widths for corresponding
th
andtd
elements to prevent misalignment between header and body during scrolling.
javascript html css