Explain Codes LogoExplain Codes Logo

How can I hide an HTML table row <tr> so that it takes up no space?

html
responsive-design
css
best-practices
Alex KataevbyAlex Kataev·Feb 10, 2025
TLDR

To totally eliminate a table row (<tr>), apply the CSS display property and set it to none:

<style> .collapse { display: none; /* Adiós amigo! */ } </style> <table> <tr class="collapse"> <td>No space occupied here!</td> </tr> <tr> <td>I'm still around!</td> </tr> </table>

Add collapse class to the <tr> you wish to vanish. Poof, it disappears without space occupancy.

Understanding deeper

While making a table row disappear is simple enough, there are few nuances with respect to the effect on table layout and border impact. Let's dive deep!

Handling border and maintaining layout

Setting display: none; may cause adjacent borders to double up or appear inconsistent. So, always apply border-collapse: collapse; to your <table> for uniform borders.

Dynamic show/hide using JavaScript

For dynamic interaction based on user activities, JavaScript could help toggle visibility:

function toggleRowVisibility(rowId) { let row = document.getElementById(rowId); row.style.display = row.style.display === 'none' ? '' : 'none'; // on-off switch }

Always ensure cross-browser compatibility and watch out for impact on other styles/scripts.

For complex layouts: alternate avenues

In complex layouts, to avoid any distortion while hiding a row with display: none;, alternate CSS properties could be helpful. visibility: collapse; or setting height: 0; and overflow: hidden;. Remember, visibility: collapse; is table-element centric and act pretty much like display: none; but reserves the space for cells and borders.

Implementing spacers for alignment

To maintain alignment when rows are hidden, consider using spacers. These are empty <td> elements with a fixed width that preserve cell layout.

Teamwork makes the dream work

Working as a team on a project? Discuss these techniques to ensure they gel with your overall styling. It's also a great chance to brainstorm clever solutions to layout challenges.

Compatibility checks and conflict resolution

Lastly, always test your solutions across different browsers. If a conflict with another style or script arises, consider some rework or add specificity to your selectors to resolve the issue.