The proper way is using col
elements with visibility: collapse
.
<colgroup>
<col />
<col />
<col />
</colgroup>
col:nth-child(2) {
visibility: collapse;
}
table, th, td, tr {
border: 1px solid black;
}
table {
width: 100%;
}
col:nth-child(2) {
visibility: collapse;
}
<table>
<colgroup>
<col />
<col />
<col />
</colgroup>
<thead>
<tr>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
</tbody>
</table>
This way will work properly even if you use colspan
.
However, note the layout of the table will be calculated before hiding the columns. And at the end, the remaining columns won't grow to make the table respect width: 100%
. As described in Dynamic effects, this avoids expensive re-layout operations. To compensate this, you can increase the width of the table beyond 100%
.
div {
overflow: hidden;
margin: 20px 0;
}
table, th, td, tr {
border: 1px solid black;
}
table {
width: 100%;
table-layout: fixed;
}
table.grow {
width: 150%;
}
col.hidden {
visibility: collapse;
}
<div>
Full table
<table>
<colgroup>
<col />
<col />
<col />
</colgroup>
<thead>
<tr>
<th colspan="2">A B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td colspan="2">Eve Jackson</td>
<td>94</td>
</tr>
</tbody>
</table>
</div>
<div>
Hiding last column
<table>
<colgroup>
<col />
<col />
<col class="hidden" />
</colgroup>
<thead>
<tr>
<th colspan="2">A B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td colspan="2">Eve Jackson</td>
<td>94</td>
</tr>
</tbody>
</table>
</div>
<div>
Hiding last column and enlarging table
<table class="grow">
<colgroup>
<col />
<col />
<col class="hidden" />
</colgroup>
<thead>
<tr>
<th colspan="2">A B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td colspan="2">Eve Jackson</td>
<td>94</td>
</tr>
</tbody>
</table>
</div>