9

Is there a way to hide table rows without affecting the overall table width? I've got some javascript that shows/hides some table rows, but when the rows are set to display: none;, the table with shrinks to fit the contents of the visible rows.

Wilco
  • 32,754
  • 49
  • 128
  • 160
  • Linking to [question with answer](https://stackoverflow.com/questions/25807564/hiding-a-tr-while-still-involving-it-in-width-calculations) for anyone looking for a modern solution: all relevant browsers support `visibility: collapse` (for rows and columns) which is specifically designed for that use case. – Martin Apr 05 '22 at 12:09

5 Answers5

9

If you are looking to preserve the overall width of the table, you can check it prior to hiding a row, and explicitly set the width style property to this value:

table.style.width = table.clientWidth + "px";
table.rows[3].style.display = "none";

However, this may cause the individual columns to reflow when you hide the row. A possible way to mitigate this is by adding a style to your table:

 table {
  table-layout: fixed;
 }
levik
  • 114,835
  • 27
  • 73
  • 90
8

CSS rule visibility: collapse was designed exactly for that.

tbody.collapsed > tr {
    visibility: collapse;
}

After adding this CSS you could trigger visibility from JS with:

tbody.classList.toggle('collapsed');
Klesun
  • 12,280
  • 5
  • 59
  • 52
3

For reference, levik's solution works perfectly. In my case, using jQuery, the solution looked something like this:

$('#tableId').width($('#tableId').width());
Wilco
  • 32,754
  • 49
  • 128
  • 160
2

In CSS, table-layout: fixed; on your table instructs the browser to honor the sizes you've specified for heights and widths. This generally suppresses auto-resizing by the browser unless you haven't given any hints as to the preferred sizes of your rows and columns.

pcorcoran
  • 7,894
  • 6
  • 28
  • 26
0

You can do it using pure HTML

<table border="1">
  <colgroup>
    <col width="150px" />
    <col width="10px"  />
    <col width="220px" />
  </colgroup>
  <tr>
    <td valign="top">1</td>
    <td> </td>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
    <td> </td>
    <td>4</td>
  </tr>
</table>
anastaciu
  • 23,467
  • 7
  • 28
  • 53
labilbe
  • 3,501
  • 2
  • 29
  • 34