Explain Codes LogoExplain Codes Logo

Controlling Spacing Between Table Cells

html
responsive-design
best-practices
layout
Anton ShumikhinbyAnton Shumikhin·Feb 2, 2025
TLDR

To adjust the space between table cells accurately, modify the border-spacing CSS property if you're using traditional tables. For no space, apply border-spacing: 0; on the table and add padding on td for desired inner cell spacing. Here's a quick example:

<style> table { border-spacing: 0; /* Who needs space anyway? */ } td { padding: 10px; /* Our lovely padding inside cells */ } </style> <table> <tr><td>Content</td><td>Content</td></tr> <tr><td>Content</td><td>Content</td></tr> </table>

Simply adjust padding to control the inner cell space.

DIY cell separation

If you require visual separation without any color bleed from the cell background, employ border-spacing combined with a transparent border. Here's how you can add that finesse:

<style> table { border-collapse: separate; border-spacing: 5px; } td { border: 5px solid transparent; /* The old invisibility cloak trick hmm? */ } </style>

This sneaky flexibility maintains a clean layout even with stylish backgrounds.

Handling legacy browsers

To deal with older browsers like Internet Explorer, there's the old expression() trick in border-collapse. Note, this isn't the best, and it's deprecated:

<style> table { /* The infamous 'expression'. Use it like a chewed pen, sparingly! */ border-collapse: expression('separate', this.borderCollapse='separate'); } </style>

Use this cautiously and always have a fallback for your hip users with latest browsers.

Layouts without tables

For non-table layouts using div elements styled as display: table-cell, remember margins don't work here. Wrap each cell in another div and use padding:

<style> .cell { display: table-cell; /* It's a cell, I swear! */ } .cell-wrapper { padding: 10px; /* Yes, you're basically cheating 'cellspacing' */ } </style> <div style="display: table;"> <div class="cell-wrapper"> <div class="cell">Content</div> </div> <div class="cell-wrapper"> <div class="cell">Content</div> </div> </div>

A nice workaround to achieve a table-like layout without ever whispering '<table>'.

Fancy separators

For finer control over styles, make use of separating backgrounds by defining classes like:

<style> .separating-bg { background-image: linear-gradient(to right, #fff, #fff 50%, transparent 50%); background-size: 21px 1px; background-repeat: repeat-x; } </style>

Just add .separating-bg class to a table row or cell to craft custom separators without disturbing the actual cell spacing.

Wrapping up

Remember, practice makes perfect. If you found the answer useful, show some love! See you at the top of the vote scale, and happy coding!👩‍💻