LonelyPixel LonelyPixel - 6 months ago 14
CSS Question

Why do the CSS property border-collapse and empty-cells conflict?

I can use the CSS property

border-collapse
to combine the borders of adjacent table cells. And I can use
empty-cells
to hide table cells that have no content. But when I use both, the
empty-cells
property has no effect and empty cells are always visible. At least there's a border around each of them, even where multiple adjacent rows and columns are empty.

Here's an example:



<!doctype html>
<html>
<head>
<style>
table
{
border-collapse: collapse;
border-spacing: 0;
}
th,
td
{
empty-cells: hide;
border: solid 1px black;
padding: 2px 4px;
}
</style>
</head>

<body>
<table>
<tr>
<th></th>
<th></th>
<th>Header 3</th>
</tr>
<tr>
<th></th>
<th></th>
<th>Header 3</th>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td></td>
</tr>
<tr>
<td>Cell 1</td>
<td>Cell 2</td>
<td></td>
</tr>
</table>
</body>
</html>




Answer

As @Bolt explained why this happens, I will provide a solution for this, you can use the below snippet in your CSS to hide the empty cells

th:empty, td:empty {
    border: 0;
}

Demo

Using :empty pseudo, I set the border: 0; so physically the element is present on the page, we just target the styles of the empty cells and set the borders to 0.

I didn't used display: none; as it will spoil your table layout, so using the above snippet is enough if you want to keep the border collapsed.

Note: The selector am using is a general selector and will target globally, if you want to target the element specifically, consider using a class instead like

.table_class_name th:empty, 
.table_class_name td:empty { 
    /* Styles goes here */
}