How to Add a Border Inside the Table

Sometimes, working with tables can cause some difficulties, for example, when you need to add a border only inside the table. Fortunately, there are some solutions to this problem that we are going to demonstrate in this snippet.

Solutions with CSS

The problem with setting a border inside the table is adding a full border around all the cells. As a result, you add a border around the whole table. Instead of it, add a border everywhere, and then remove the border where needed. For that, you’ll need the border-collapse property with the “collapse” value, the :first-child and :last-child pseudo-classes.

Example of adding a border inside the table:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      table {
        border-collapse: collapse;
      }
      table td,
      table th {
        border: 1px solid #000;
      }
      table tr:first-child th {
        border-top: 0;
      }
      table tr:last-child td {
        border-bottom: 0;
      }
      table tr td:first-child,
      table tr th:first-child {
        border-left: 0;
      }
      table tr td:last-child,
      table tr th:last-child {
        border-right: 0;
      }
    </style>
  </head>
  <body>
    <table>
      <tr>
        <th>Heading 1</th>
        <th>Heading 2</th>
      </tr>
      <tr>
        <td>Lorem Ipsum</td>
        <td>Lorem Ipsum</td>
      </tr>
      <tr>
        <td>Lorem Ipsum</td>
        <td>Lorem Ipsum</td>
      </tr>
    </table>
  </body>
</html>

Result

Heading 1 Heading 2
Lorem Ipsum Lorem Ipsum
Lorem Ipsum Lorem Ipsum

Another way of setting a border only inside the table is using the CSS border-style property set to “hidden”. This value has a higher priority over the table cell and border collapsing.

So, setting the border-style property with the “hidden” value on the table will not display the external borders. Let’s see it.

Example of adding a border inside the table with the border-style property:

<!DOCTYPE html>
<html>
  <head>
    <title>Title of the document</title>
    <style>
      table {
        margin: 0 auto;
        border-collapse: collapse;
        border-style: hidden;
      }
      table td {
        padding: 30px;
        border: 3px solid #0044b3;
      }
    </style>
  </head>
  <body>
    <table>
      <tr>
        <td>Lorem Ipsum</td>
        <td>Lorem Ipsum</td>
        <td>Lorem Ipsum</td>
      </tr>
      <tr>
        <td>Lorem Ipsum</td>
        <td>Lorem Ipsum</td>
        <td>Lorem Ipsum</td>
      </tr>
    </table>
  </body>
</html>