Home > Mobile >  CSS selector to match the first empty element
CSS selector to match the first empty element

Time:03-21

I'm looking to apply some styles to the first element of the parent which is empty and a certain type. For example, I have a table something like this

<table>
  <tr>
    <th>1</th>
    <td>a</td>
    <td>b</td>
    <td></td> <!-- this should be matched -->
  </tr>
  <tr>
    <th>2</th>
    <td>c</td>
    <td></td> <!-- this should be matched -->
    <td></td> <!-- this should not be matched -->
  </tr>
</table>

I want to match only the first td in each row which has no content. I've tried this

td:empty:first-of-type {
  background-color: red;
}

But that only applies to elements which are both the first of type and empty (e.g. if the cell with 'a' or 'c' was empty), rather than the first empty cell. If I could group selectors like

(td:empty):first-of-type

that would produce the correct result in my head as it would look for the first td:empty but obviously that's not valid CSS and not how the :first-of-type selector works, as that only considers type.

Is it possible to do this using just CSS?

CodePudding user response:

I am afraid you need a bit more complex combination. First, select all empty, then exclude those that follow any other empty.

td:empty:not(td:empty ~ td:empty) {
  ...
}

Example

td {
  background: blue;
  width: 20px;
}

td:empty:not(td:empty ~ td:empty) {
  background: red
}
<table>
  <tr>
    <th>1</th>
    <td>a</td>
    <td>b</td>
    <td></td> <!-- this should be matched -->
    <td>4</td>
    <td></td> <!-- this should not be matched -->
  </tr>
  <tr>
    <th>2</th>
    <td>c</td>
    <td></td> <!-- this should be matched -->
    <td></td> <!-- this should not be matched -->
    <td>4</td>
    <td></td> <!-- this should not be matched -->
  </tr>
</table>

  • Related