I am working on a table that can have no headers, the first row as a header, the first column as a header, or both the first column and the first row as headers.
The expected output is that the headers should have a border on the right, except when the first row is set as the header
The issue is that I am getting a border-right even when the first row is set as the header. Is there a solution to avoid this?
table {
border: 1px solid #D2D2D2;
border-collapse: collapse;
th {
padding: 16px;
border-right: 1px solid #D2D2D2;
background: #F1F1F1
}
td {
padding: 16px;
}
tr {
border-bottom: 1px solid #D2D2D2;
}
tr:first-child th:not(:first-child) {
border-right: 0;
}
}
<p> Table with first row as header</p>
<table>
<tbody>
<tr>
<th>Fruits</th>
<th>Veggies</th>
<th>Junks</th>
</tr>
<tr>
<td>Apple</td>
<td>Carrot</td>
<td>Burger</td>
</tr>
<tr>
<td>Orange</td>
<td>Betroot</td>
<td>Fries</td>
</tr>
</tbody>
</table>
<p> Table with first column as header</p>
<table>
<tbody>
<tr>
<th>Fruits</th>
<td>Veggies</td>
<td>Junks</td>
</tr>
<tr>
<th>Apple</th>
<td>Carrot</td>
<td>Burger</td>
</tr>
<tr>
<th>Orange</th>
<td>Betroot</td>
<td>Fries</td>
</tr>
</tbody>
</table>
<p> Table with first row and column as header</p>
<table>
<tbody>
<tr>
<th>Fruits</th>
<th>Veggies</th>
<th>Junks</th>
</tr>
<tr>
<th>Apple</th>
<td>Carrot</td>
<td>Burger</td>
</tr>
<tr>
<th>Orange</th>
<td>Betroot</td>
<td>Fries</td>
</tr>
</tbody>
</table>
<p>Table with no header</p>
<table>
<tbody>
<tr>
<td>Fruits</td>
<td>Veggies</td>
<td>Junks</td>
</tr>
<tr>
<td>Apple</td>
<td>Carrot</td>
<td>Burger</td>
</tr>
<tr>
<td>Orange</td>
<td>Betroot</td>
<td>Fries</td>
</tr>
</tbody>
</table>
NOTE : I don’t have access to add/modify the HTML or add JS. Also the order of the tables here are just for example, it changes based on the requirement
2
Answers
You can fix this using CSS.
I have added
&:nth-of-type(1) tr:first-child th { border-right: 0; }
nth-of-type(1) – Select only first Table
tr:first-child – Select first header row of first Table
For more info you can check MDN documentation
Link – https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type
Updated Code is below.
The border-right is removed for all headers in the first row except the first column (using :not(:first-child)).
A specific rule ensures that the first column headers (th:first-child) always retain their border-right style, even when it’s part of a table that also has the first row as a header