skip to Main Content

here is my html/css code:

<style>
td{
  padding:30px;
  box-shadow: 0 0 5px 5px lightgray;
}
</style>
<table>
  <tr>
    <td>1</td><td>2</td>
  </tr>
  <tr>
    <td>3</td>
  </tr>  
</table>

this produces the the folowing output

enter image description here

my question is: is there a way to make the box-shadow not affect the adjacent td?

here is the required output:

enter image description here

2

Answers


  1. Consider using filter: drop-shadow on the table element. This way all solid child elements are treated as a whole to make a single instance of a shadow.

    table {
      /* to prevent "gaps" between cells */
      border-collapse: collapse; 
      filter: drop-shadow(0px 0px 10px lightgray);
    }
    
    td {
      padding: 30px;
      /* child elements need to have a solid background in order to cast a shadow */
      background-color: white;
    }
    <table>
      <tr>
        <td>1</td>
        <td>2</td>
      </tr>
      <tr>
        <td>3</td>
      </tr>
    </table>

    But be aware it doesn’t support spread option like box-shadow does, to achieve heavier shadows, you might want to add more shadow instances to the filter:

    filter: drop-shadow(0px 0px 5px lightgray) drop-shadow(0px 0px 10px lightgray);
    
    Login or Signup to reply.
  2. @HaoWu’s answer is excellent. Here is another approach.

    Apply the box shadow to a pseudo-element and have a same stacking context for all tds so that you can push all the pseudo element behind all tds.

    This requires you to set the --row and --col CSS variables on each td element. You could also use javascript for setting them.

    * {
      box-sizing: border-box;
      --size: 50px;
    }
    
    tbody {
      position: relative;
    }
    
    td {
      position: absolute;
      width: var(--size);
      height: var(--size);
      background: white;
      
      display: grid;
      place-items: center;
      
      left: calc(var(--size) * var(--col));
      top: calc(var(--size) * var(--row));
    }
    
    td::before {
      content: '';
      position: absolute;
      z-index: -1;
      width: inherit;
      height: inherit;
      box-shadow: 0 0 10px 5px lightgray;
    }
    <table>
      <tbody>
        <tr>
          <td style="--row: 0; --col: 0;">1</td>
          <td style="--row: 0; --col: 1;">2</td>
        </tr>
        <tr>
          <td style="--row: 1; --col: 0;">3</td>
        </tr>
      </tbody>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search