Alex Wohlbruck
Alex Wohlbruck

Reputation: 1436

Add box-shadow to tbody in CSS?

I am trying to recreate this material design table I made in a Photoshop mockup:

enter image description here

I've got everything I want except for a drop shadow. When I apply a drop shadow to the tbody element, it shows in Firefox, but not Chrome or Edge.If I apply a "display: block" style to it as well, it will show. However, this removes the default "display: table-row-group" style, effectively ruining the structure of the table. How can I add a drop shadow without affecting the rest of the layout?

* {
  font-family: Roboto, Arial;
}

body {
  background: #f8f8f8;
}

table {
  border-collapse: collapse;
  width: 100%;
}

th {
  font-weight: normal;
  opacity: .7;
  text-align: left;
  padding-left: 20px;
  padding-bottom: 10px;
}

td {
  padding: 20px;
}

tbody tr:nth-child(even) {
  background: rgba(128,128,128,.05);
}

tbody {
  background: #fff;
  
  /* This doesn't work unless "display: block" is applied, which ruins the structure */
  box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12);
  -moz-box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12);
  -webkit-box-shadow: 0 2px 5px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12);
}

.grey {
  opacity: .5;
}

.green {
  color: #4caf50;
}
<table>
  <thead>
    <tr>
      <th>Name</th>
      <th>Date</th>
      <th>Grade</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>You</td>
      <td>Today, 4:12 PM</td>
      <td class="green">92%</td>
    </tr>
    <tr>
      <td>John Smith</td>
      <td>Today, 3:28 PM</td>
      <td class="grey">Hidden</td>
    </tr>
    <tr>
      <td>Bobby Newport</td>
      <td>Yesterday</td>
      <td class="grey">Hidden</td>
    </tr>
    <tr>
      <td>Jim Halpert</td>
      <td>2 days ago</td>
      <td class="grey">Hidden</td>
    </tr>
    <tr>
      <td>Detlow Coffin</td>
      <td>2 days ago</td>
      <td class="grey">Hidden</td>
    </tr>
  </tbody>
</table>

Upvotes: 2

Views: 1818

Answers (2)

Christophe
Christophe

Reputation: 953

I spent a few hours on this issue and have finally a working solution that doesn't break the table layout. But now that I think about it flexbox would probably be much simpler...

table {
  position: relative;
}

table:after {
  content: '';
  position: absolute;
  box-shadow: 0 2px 4px 0 rgba(37, 37, 37, 0.2); // your box-shadow
  left: 0;
  right: 0;
  top: 36px; // height of your table header
  bottom: 0;
  z-index: -1;
}

Here is the fiddle: https://jsfiddle.net/jitowix/o2gx7sc4/

Upvotes: 5

Christian Bonato
Christian Bonato

Reputation: 1306

Add a property of

display:table;

or

display:inherit;

to tbody and see what happens.

You can also try :before and :after.

Upvotes: -1

Related Questions