CSS: TD background color causing borders to disappear

keewee279 picture keewee279 · Jun 5, 2015 · Viewed 11.4k times · Source

I have a large HTML table that is created dynamically. The table has a standard structure, incl. colgroup, thead and tbody and the below styles.

So far everything works as intended but when I add the class "bgGrey" to the TDs in one column (see below) in order to give the cells in this column a background color (which is only needed on one column) then all borders of this column disappear in IE11, except for the left border, and the :hover::before style doesn't work anymore in Chrome (version 43).
Without adding the class "bgGrey" I have no issues in both browsers.

It seems that somehow the background color overlaps the border causing this.

My CSS (relevant part):

#myTable, #myTable tbody, #myTable thead, #myTable tr {
    width: 100%;
}
#myTable, #myTable th, #myTable td {
    border: 1px solid #000;
    border-collapse: collapse;
    margin: 0;
    padding: 4px;
    position: relative;
}
#myTable {
    font-size: 14px;
    table-layout: fixed;
}
#myTable th.editable:hover::before, #myTable td.editable:hover::before {
    border: 1px solid blue;
    content: '';
    position: absolute;
    top: 0; right: 0; bottom: 0; left: 0;
    z-index: -1;
}
#myTable .th1 {
    padding: 2px;
}
#myTable .th2 {
    font-weight: normal;
}

.bgGrey {
    background-color: #e6e6e6;
}

My HTML (example TR):

<tr>
    // ...
    <td class="editable"><div contenteditable="true"></div></td>
    <td class="bgGrey editable txtCenter"><div contenteditable="true"></div></td>
    <td class="editable txtRight"><div contenteditable="true"></div></td>
    // ...
</tr>

Answer

pusle picture pusle · Feb 28, 2018

I just came upon this problem myself, but I didn't like the solution presented here, so I kept googling. I found this answer: https://stackoverflow.com/a/16337203/1156476

Here, a simple addition to the table cell fixes the borders:

table td {
  border: 1px solid #000;
  border-collapse: collapse;
  margin: 0;
  padding: 4px;
  position: relative;
  background-clip: padding-box; /* Add this line */
}

Check browser support at Caniuse

And an explanation of the property can be found at Standardista