Search code examples
htmlcssz-indexbox-shadow

Background color hiding other box-shadow


I have a table, and I want to set some styling when you hover a row, so I used box-shadow, and added the corresponding z-index to make this work. The problem is that when I set the tds to have a background color, it just makes it be on top of the box-shadow, and therefore the hover does not work.

How can I fix this so that I can have both a background-color in the td elements, and do the box-shadow style when hovering on a row?

I reproduced it in this simple jsfiddle: https://jsfiddle.net/pjz43a52/

Check that when you hover on a row, the box-shadow is behind the other rows. If you comment the line for the td background-color, it just works:

table td {
  /* background-color: #EFEFEF; */
  z-index: 1;
}

Any ideas why would this happen?


Solution

  • This happens because td is a child of tr. When your CSS sets tr to have a higher z-index than td on hover, it will be rendered above the surrounding cells so you can see the shadow cast on its neighbours. However no shadow can be cast on its own child td as they are also raised with their parent.

    You need to set your parent row to appear above its own children. One way you might achieve this is by setting td z-index to -1 and removing all z-indexes from tr. Doing this does make the row's shadow to display over top of all cells, including its own children, but in both Chrome and Firefox the rendering is awful.

    To get this to work you must also ensure that every element affected by a z-index change has its position property set to non static.

    table tr {
      position: relative;
    }
    
    table td {
      position:relative;
      background-color: #EFEFEF;
      z-index: -1;
    }
    
    table tr:hover {
      position: relative;
      box-shadow: 
        inset 5px 0 0 #dadce0, 
        inset -3px 0 0 #dadce0, 
        0 5px 2px 0 rgba(60,64,67,.3), 
        0 5px 3px 1px rgba(60,64,67,.15);
    }