Explain Codes LogoExplain Codes Logo

How to hide columns in an HTML table?

html
responsive-design
css
javascript
Nikita BarsukovbyNikita Barsukov·Oct 28, 2024
TLDR

The answer to your problem is pretty simple: you use CSS to hide table columns. Just apply display: none; to your column headers (<th>) and data cells (<td>). Here's the basic idea:

.hide-column { display: none; }

Now just sprinkle some .hide-column fairydust to your HTML elements:

<tr> <th>Shown</th> <th class="hide-column">Hidden</th> </tr> <tr> <td>Data</td> <td class="hide-column">No-Show</td> </tr>

And like magic, the column disappears! Apply the class to any column you wish to vanish.

Adding dynamism using JavaScript

If CSS doesn't cut it for you, say hello to JavaScript. Here is an example function that toggles column visibility:

function toggleColumnVisibility(columnIndex) { // Get the party hats, er, table columns var cols = document.querySelectorAll(`td:nth-child(${columnIndex}), th:nth-child(${columnIndex})`); cols.forEach(function (col) { // Now for some magic tricks col.style.display = col.style.display === 'none' ? '' : 'none'; }); }

To toggle let's say the second column, just call it like toggleColumnVisibility(2);.

Managing space using CSS

To hide the content while preserving its space, you can use visibility: hidden; instead:

.preserve-space-column { visibility: hidden; }

The column still occupies space, but your secret is safe — the data won't show.

For the responsive minds

Thanks to media queries in CSS, you can hide columns based on the device's width:

@media (max-width: 600px) { .responsive-hide { display: none; } }

Use .responsive-hide to make columns disappear on smaller devices.

Playing well with jQuery and Bootstrap

For best compatibility, use jQuery to handle the dirty work:

// Hide the second column $('td:nth-child(2), th:nth-child(2)').hide();

For those using Bootstrap, the .hidden class gets the job done:

<th class="hidden-xs">Age</th> <td class="hidden-xs">29</td>

The "Age" column pulls a disappearing act on extra-small devices.

Special use-cases: custom solutions

When life throws you curveballs, you need a custom approach.

  • Generate tables on the server-side with only the columns needed.
  • Design data attributes for flexible display conditions.
<td data-hide-on-mobile>29</td>

Data attr like these can drive JS for dynamic or conditional display.

Problem-solving (aka debugging) and future-proofing

While hiding columns, keep an eye out for these common issues:

  • Wrong elements disappearing: Make sure your selectors are accurate.
  • Layout breaks: Hidden elements can affect table layout. Test, and adjust if needed.
  • Unwanted CSS cascades: Be specific with CSS selectors to avoid affecting other elements.