Select parent of empty elements using Sass or CSS

2019-03-03 22:56发布

问题:

I've tried several combinations to try and select a parent row but nothing seems to work. Maybe it is not possible. If someone could help explain how to achieve this through either css or sass it would be much appreciated.

The goal is to add a gray background to a row, , if that row contains an empty column, .


I've tried some variations of the following:

tr > td:empty {
  background-color: #f3f3f3;
}

Example

<table>
   <thead></thead>
   <tbody>
        <tr>
        <td>No</td>
        <td>empty</td>
        <td>cells</td>
        <td>here</td>
    </tr>
    <tr>
        <td>Does</td>
        <td>have</td>
        <td>empty</td>
        <td>cell</td>
        <td></td>
    </tr>
   </tbody>
   <tfoot></tfoot>
</table>

回答1:

There is not such selector to do this but you can simulate the effect using a pseudo element:

table {
  overflow: hidden;
  position: relative;
  z-index: 0;
}

tr>td:empty {
  position: relative;
}

tr>td:empty::before {
  content: "";
  position: absolute;
  z-index: -1;
  top: 0;
  left: -50vw;
  right: -50vw;
  bottom: 0;
  background-color: #f3f3f3;
}
<table>
  <thead></thead>
  <tbody>
    <tr>
      <td>No</td>
      <td>empty</td>
      <td>cells</td>
      <td>here</td>
    </tr>
    <tr>
      <td>Does</td>
      <td>have</td>
      <td>empty</td>
      <td>cell</td>
      <td></td>
    </tr>
  </tbody>
  <tfoot></tfoot>
</table>
<table>
  <thead></thead>
  <tbody>
    <tr>
      <td></td>
      <td>empty</td>
      <td>cells</td>
      <td></td>
      <td>here</td>
    </tr>
    <tr>
      <td>Does</td>
      <td>have</td>
      <td></td>
      <td>empty</td>
      <td>cell</td>
    </tr>
  </tbody>
  <tfoot></tfoot>
</table>



标签: html css sass