Spacing between columns in a table

user5993915 picture user5993915 · Jun 8, 2017 · Viewed 21.7k times · Source

I have a big problem with the spacing of columns in a table. Here's what I'd like to get, spacing only between <td>:

enter image description here

Not working with margin, padding or border:

enter image description here

Not working with border-spacing:

enter image description here

And if use first-child and last-child, same problem as previous image.

Solution I found, but really dirty:

.spacer {
  width: 15px;
  height: 15px;
}
<td></td>
<div id="spacer"></div>
<td></td>
<div id="spacer"></div>
<td></td>
<div id="spacer"></div>
<td></td>

Answer

Luckness picture Luckness · Jun 8, 2017
  1. Use border-spacing: 15px 0px to generate only horizontal spacing;
  2. To not display only left and right spacing, you can wrap the table in a div, and set margin: 0px -15px to table. Then, set overflow: hidden; to div how hide extra left and right spacing.

td {
  padding-left: 7.5px;
  padding-right: 7.5px;
  background-color: red;
  height: 40px;
  border: 1px solid green;
  width: 25%;
}

td:first-child {
  padding-left: 0;
}

td:last-child {
  padding-right: 0;
}

table {
  width: calc(100% + 30px);
  table-layout: fixed;
  border-spacing: 15px 0px;
  background: green;
  margin: 0px -15px;
}

.table-container {
  overflow: hidden;
  width: 400px;
  margin: 0 auto;
}
<div class="table-container">
  <table>
    <tr>
      <td></td>
      <td></td>
      <td></td>
      <td></td>
    </tr>
  </table>
</div>