How to Hide Empty Table Cells Using CSS?

If you wish to hide empty table cells, then you can do either of the following:

  1. Use empty-cells Property;
  2. Use :empty Pseudo-Class.

For all examples in this post, you can assume a <table> like the following:

<table>
  <thead>
    <tr>
      <th></th>
      <th>Foo</th>
      <th>Bar</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Baz</td>
      <td></td>
      <td>✓</td>
    </tr>
    <tr>
      <td>Qux</td>
      <td>✓</td>
      <td></td>
    </tr>
  </tbody>
</table>

To visibly see the styling, you can add, for example, the following border and background to <td> and <th> elements:

th, td { border: 1px solid red; background-color: pink; }

Using empty-cells Property

The empty-cells CSS property determines if borders and backgrounds are applied to <table> cells that have no visible content. For example, when its value is set to hide, it won't draw any borders or apply any background properties to empty <table> cells.

You can specify empty-cells property on the <table> element, like so:

table { empty-cells: hide; }

This would hide all empty cells in <th> and <td> elements.

The empty-cells property is not very well-known, however, it has very good browser support.

Using :empty Pseudo-Class

You can use the :empty pseudo-class on <th> and/or <td> to hide elements that have no children — i.e. element nodes or text (including whitespace).

For example, to hide empty <th> and <td> elements, you can do the following:

th:empty, td:empty { visibility: hidden; }

Using :empty gives you more control and flexibility over which <table> cells you want to hide. For example, you could exclude either <th> or <td> easily, or you may even combine it with other selectors, such as :nth-child, etc.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.