1

I'm restyling a legacy app, changing only the .css behind it. In a simplified scenario I have something like this:

table {
  border: 1px solid black;
}

div.name {
  background-color: red;
}

div+td {
  background-color: yellow;
}
<table>
  <tr>
    <td>
      <div class='name'>Sean</div>
    </td>
    <td>Connery</td>
    <td>1</td>
  </tr>
  <tr>
    <td>
      <div class='name'>Pierce</div>
    </td>
    <td>Brosnan</td>
    <td>2</td>
  </tr>
</table>

I'd like to find a way (with pure css) to set background color for td elements immediately after the td that contain the div with class='name'. In other words I'd like to set background color for cells with 'Connery' and 'Brosnan'.

In my example I've used the selector div + td which is obviously wrong.

Here the fiddle.

andreas
  • 16,357
  • 12
  • 72
  • 76
willy
  • 155
  • 7

1 Answers1

1

There is no "next same parent" selector in CSS. You can use the :nth-child selector to always select the second td:

td:nth-child(2) {...}

table {
  border: 1px solid black;
}

div.name {
  background-color: red;
}

td:nth-child(2) {
  background-color: yellow;
}
<table>
  <tr>
    <td>
      <div class='name'>Sean</div>
    </td>
    <td>Connery</td>
    <td>1</td>
  </tr>
  <tr>
    <td>
      <div class='name'>Pierce</div>
    </td>
    <td>Brosnan</td>
    <td>2</td>
  </tr>
</table>

Or (as suggested in the comments), move your class="name" to the td element and use the adjacent sibling selector +:

.name + td {...}

table {
  border: 1px solid black;
}

.name {
  background-color: red;
}

.name + td {
  background-color: yellow;
}
<table>
  <tr>
    <td class='name'>
      <div>Sean</div>
    </td>
    <td>Connery</td>
    <td>1</td>
  </tr>
  <tr>
    <td class='name'>
      <div>Pierce</div>
    </td>
    <td>Brosnan</td>
    <td>2</td>
  </tr>
</table>
andreas
  • 16,357
  • 12
  • 72
  • 76