How to hide columns in an HTML table?
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:
Now just sprinkle some .hide-column
fairydust to your HTML elements:
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:
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:
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:
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:
For those using Bootstrap, the .hidden
class gets the job done:
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.
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.
Was this article helpful?