skip to Main Content

How to write CSS selector that given this table

<table>
  <tr>
    <td>Cell 1</td>
    <td class="target">Cell 2</td>
    <td class="target">Cell 3</td>
    <td>Cell 4</td>
  </tr>
  <tr>
    <td class="target">Cell 5</td>
    <td>Cell 6</td>
    <td>Cell 7</td>
    <td class="target">Cell 8</td>
  </tr>
</table>

selects only "Cell 2" and "Cell 5"? The order of which cell might have the class name is random for each row. The only guarantee is each row must have at least one cell with the class.

I’ve tried something like td.target:first-of-type, but selectors like this apply the pseduo class first then restrict on the class name, resulting "Cell 5". I need to apply the class name first, while maintaining its n-th child state, then apply the :first-of-type.

Is this possible?

2

Answers


  1. You can target all the .target elements, that are not a .target following a .target 🙂

    .target:not(.target ~ .target) { color: red }
    <table>
      <tr>
        <td>Cell 1</td>
        <td class="target">Cell 2</td>
        <td class="target">Cell 3</td>
        <td>Cell 4</td>
      </tr>
      <tr>
        <td class="target">Cell 5</td>
        <td>Cell 6</td>
        <td>Cell 7</td>
        <td class="target">Cell 8</td>
      </tr>
    </table>
    Login or Signup to reply.
  2. you can use nth-child()

    td:nth-child(1 of .target) { color: red }
    <table>
      <tr>
        <td>Cell 1</td>
        <td class="target">Cell 2</td>
        <td class="target">Cell 3</td>
        <td>Cell 4</td>
      </tr>
      <tr>
        <td class="target">Cell 5</td>
        <td>Cell 6</td>
        <td>Cell 7</td>
        <td class="target">Cell 8</td>
      </tr>
    </table>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search