Explain Codes LogoExplain Codes Logo

Html table needs spacing between columns, not rows

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

To add spacing exclusively to the columns of an HTML table, utilize the CSS border-spacing property:

table { border-collapse: separate; border-spacing: 10px 0; }

Here, border-collapse: separate; ensures individual column borders aren't merged. Then border-spacing: 10px 0; introduces 10px horizontal space, leaving the row spacing untouched.

CSS classes for modulating spacing

For consistent column spacing across an HTML table, reusable CSS classes are a lifesaver.

Central CSS decision-making

Inline CSS styles can become tangled webs. Avoid them by centralizing your CSS either in an external stylesheet or nested in your <head>:

/* CSS stylesheet or <head> section */ .table-cell-spacing { padding-right: 15px; /* Good ol' right padding for that airy feel! */ } td { padding-left: 0; /* Bye bye default padding, hello symmetry! */ }

You can then use this defined class on your HTML table cells:

<td class="table-cell-spacing">Data 1</td> <td class="table-cell-spacing">Data 2</td>

Harnessing the power of CSS selectors

In cases where classes aren't an option or legacy code discourages edit, use a nifty CSS table-cell selector:

/* "Excuse me while I space out (get it?) the siblings!" */ tr > * + * { padding-left: 15px; }

This selector adds padding to every element in a <tr>. No generous amounts of whitespace at the line start, but evenly spread out padding.

A few hidden snags

Applying column spacing in HTML tables invites minor complications.

Layout Impact

Layout disruption during column spacing adverseky affects table appearance. Experiment with different padding values to find the optimal design.

Back-alley methods

In the absence of CSS, a fallback option can be an extra <td> using non-breaking spaces:

<td>Data 1</td> <td>&nbsp;</td> <!-- Just an innocent `<td>`, spacing out here! --> <td>Data 2</td>

By all means, utilize it, but remember, maintainability might become a tough nut to crack.

Dark arts of code maintenance

Keeping CSS rules centralized promotes consistency and smooth future adjustments. Also, bear in mind browser compatibility while choosing methods for spacing.