skip to Main Content

example

(The grey section is thead, white section with grey border-bottom is tr in tbody)

table {
    border-collapse: collapse;
    border-spacing: 0;
}

thead {
  background: #ddd;
}

tbody tr {
  border-bottom: 1px solid #ddd;
}

th,
td {
  width: 100px;
  padding: 10px;
  text-align: start;
}
<table>
  <thead>
    <tr>
      <th>name</th>
      <th>age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>John</td>
      <td>20</td>
    </tr>
    <tr>
      <td>Sam</td>
      <td>24</td>
    </tr>
  </tbody>
</table>

I need to add a 8px margin left/right around thead, while there should be no spacing around tbody.

I have tried adding margin/padding to thead, but neither worked. I also attempted adding margin-left to the first element of thead, but it still didn’t work.

2

Answers


  1. Margins does not really make sense and does not work for table elements.

    What you can do is increase padding for first and last elements of thead th:

    table {
      border: 1px solid #ddd;
      border-collapse: collapse;
    }
    
    tbody tr {
        border-bottom: 1px solid #ddd;
    }
    
    td {
        width: 100px;
        padding: 10px;
        text-align: start;
    }
    
    thead tr th {
      padding: 0;
    }
    
    thead tr div {
        background: #ddd;
      padding: 10px;
    }
    
    thead tr th:first-child {
        padding-left: 8px;
    }
    
    thead tr th:last-child {
        padding-right: 8px;
    }
    <table>
        <thead>
            <tr>
                <th><div>name</div></th>
                <th><div>age</div></th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>John</td>
                <td>20</td>
            </tr>
            <tr>
                <td>Sam</td>
                <td>24</td>
            </tr>
        </tbody>
    </table>
    Login or Signup to reply.
  2. Not sure exactly what you want to achieve, but perhaps adding an 8px white border to the table will do what you want?

    body {
      background: #888;
    }
    
    table {
      background: white;
      border: 8px solid white;
    }
    
    thead {
        background: #ddd;
    }
    
    tbody tr {
        border-bottom: 1px solid #ddd;
    }
    
    th,
    td {
        width: 100px;
        padding: 10px;
        text-align: start;
    }
    <table>
        <thead>
            <tr>
                <th>name</th>
                <th>age</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>John</td>
                <td>20</td>
            </tr>
            <tr>
                <td>Sam</td>
                <td>24</td>
            </tr>
        </tbody>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search