Certainly! Below is an updated example where the first two columns of the table are frozen. This is achieved by extending the position: sticky styling to the second column as well.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frozen Header and First Two Columns</title>
<style>
table {
border-collapse: collapse;
width: 100%;
table-layout: fixed;
}
th, td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
/* Freeze the top row (header) */
th:first-child, th {
position: sticky;
top: 0;
z-index: 2;
}
/* Freeze the first two columns */
td:first-child, td:nth-child(2), th:first-child, th:nth-child(2) {
position: sticky;
left: 0;
z-index: 1;
}
/* Ensure the top-left cell stays on top */
th:first-child {
z-index: 3;
}
/* Ensure the top-second cell stays on top */
th:nth-child(2) {
z-index: 3;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>Header 4</th>
</tr>
</thead>
<tbody>
<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>
</tbody>
</table>
</body>
</html>
Explanation:
CSS Styling:
position: sticky is used for both the first and second columns.
left: 0 ensures the first column stays on the left.
left: 0 for the second column is adjusted to ensure it stays next to the first column.
z-index is used to control the stacking order, ensuring the top-left and top-second cells stay on top.
HTML Structure:
The table is divided into <thead> for the header row and <tbody> for the data rows.
The first two column cells (<td>:first-child, <td>:nth-child(2)) and the header cells (<th>:first-child, <th>:nth-child(2)) are styled to be sticky.
This example will freeze both the first and second columns when you scroll the table horizontally.