I have a table where I’ve applied sticky positioning to the first column using the following CSS:
th:first-child,
td:first-child {
position: -webkit-sticky; /* for Safari */
position: sticky;
z-index: 1;
left: 0;
background: #fff;
}
While this successfully makes the first column sticky, I encounter a problem when scrolling horizontally: the right border of the first column disappears. How can I resolve this issue?
Here’s my HTML and CSS setup for reference:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
* {
box-sizing: border-box;
}
.table-container {
overflow: auto;
border: solid;
margin: auto;
}
table {
width: 100%;
table-layout: fixed;
border-collapse: collapse;
}
th,
td {
width: 20%;
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
th:first-child,
td:first-child {
position: -webkit-sticky; /* for Safari */
position: sticky;
z-index: 1;
left: 0;
background: #fff;
}
</style>
</head>
<body>
<div class="table-container">
<table>
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
<th>Column 4</th>
<th>Column 5</th>
<th>Column 6</th>
<th>Column 7</th>
<th>Column 8</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data 1</td>
<td>Data 2</td>
<td>Data 3</td>
<td>Data 4</td>
<td>Data 5</td>
<td>Data 6</td>
<td>Data 7</td>
<td>Data 8</td>
</tr>
<!-- More rows as needed -->
</tbody>
</table>
</div>
</body>
</html>
How can I ensure that the right border of the first sticky column remains visible when I scroll horizontally through the table?
2
Answers
You can try using pseudo element, add the following CSS
I think this makes the trick
You just need to change
border-collapse: collapse;
intoborder-collapse: separate;
.