FrankRP
FrankRP

Reputation: 105

Style first table row of group identified by td classname sibling to another row

How can I do to change the style of the first row of a group of rows (identified by a td with a sub-item class) that is near to a sibling row (identified by a td with the item class):

HTML:

<table>
  <thead>
  </thead>
  <tbody>
    <tr>
      <td class="item"></td>
    </tr>
    <tr>
      <td class="sub-item"><!-- I need to style this one --></td>
    </tr>
    <tr>
      <td class="sub-item"></td>
    </tr>
    <tr>
      <td class="sub-item"></td>
    </tr>
    <tr>
      <td class="item"></td>
    </tr>
    <tr>
      <td class="sub-item"><!-- I need to style this one --></td>
    </tr>
  </tbody>
</table>

I'd like to style with an inset box-shadow all the first rows matched by this criteria.

I tried with the sibling operator without success:

CSS:

tr > td.item ~ tr > td.sub-item:first {}

Upvotes: 0

Views: 219

Answers (1)

dippas
dippas

Reputation: 60563

With the current code you would have to use :nth-[last]-child()

tr:first-child + tr .sub-item, tr:nth-last-child(2) + tr .sub-item {
  background-color: red
}
<table>
  <thead>

  </thead>
  <tbody>
    <tr>
      <td class="item">1</td>
    </tr>
    <tr>
      <td class="sub-item">2<!-- I need to style this one --></td>
    </tr>
    <tr>
      <td class="sub-item">3</td>
    </tr>
    <tr>
      <td class="sub-item">4</td>
    </tr>
    <tr>
      <td class="item">5</td>
    </tr>
    <tr>
      <td class="sub-item">6<!-- I need to style this one --></td>
    </tr>
  </tbody>
</table>


Also, you can add a class to tr and achieve what you want.

.row + tr .sub-item {
  background-color: red
}
<table>
  <thead>

  </thead>
  <tbody>
    <tr class="row">
      <td class="item">1</td>
    </tr>
    <tr>
      <td class="sub-item">2<!-- I need to style this one --></td>
    </tr>
    <tr>
      <td class="sub-item">3</td>
    </tr>
    <tr>
      <td class="sub-item">4</td>
    </tr>
    <tr class="row">
      <td class="item">5</td>
    </tr>
    <tr>
      <td class="sub-item">6<!-- I need to style this one --></td>
    </tr>
  </tbody>
</table>

Upvotes: 2

Related Questions