0

I have rows like this:

<tr class="team_2">Team Member</tr>
<tr class="team_2">Team Member</tr>
<tr class="team_1">Team Member</tr>
<tr class="team_2">Team Member</tr>
<tr class="team_1">Team Member</tr>

I want to highlight the first member of each team as team captain. I tried this:

table tbody tr.team_2:first-of-type, table tbody tr.team_1:first-of-type {
background: red;
}

This highlighted the first row, but not the third row (captain for team 1). Is this type of selector possible?

kmoney12
  • 4,413
  • 5
  • 37
  • 59

2 Answers2

4

You'd have to do it backwards, see this answer for more info. Basically set ALL of those classes to the highlight color, then you look further down the DOM and reset any subsequent, sibling classes to the default.

Also, you should put td elements in your table:

.team_2, .team_1 {
  background-color: red;
}

.team_1 ~ .team_1 {
  background-color: transparent;
}
.team_2 ~ .team_2 {
  background-color: transparent;
}
<table>
<tr class="team_2"><td>Team Member</td></tr>
<tr class="team_2"><td>Team Member</td></tr>
<tr class="team_1"><td>Team Member</td></tr>
<tr class="team_2"><td>Team Member</td></tr>
<tr class="team_1"><td>Team Member</td></tr>
</table>
Ben
  • 5,079
  • 2
  • 20
  • 26
  • 2
    There are `` elements in the table, I just removed them for simplification. The real rows are a lot bigger. Thanks for the cool trick! – kmoney12 Oct 04 '17 at 20:29
2

Ideally you would just add a class to the team member and target that specific class.

HTML

<tr class="team_2">
 <td class="captain">Team Member</td>
</tr>
<tr class="team_1">
 <td>Team Member</td>
</tr>
<tr class="team_1">
 <td class="captain">Team Member</td>
</tr>
<tr class="team_2">
 <td>Team Member</td>
</tr>

CSS

.captain{.....}

EDIT: I have edited my answer as the one Ben gave is better aligned to your question.

CleanCode
  • 43
  • 5