Stefan Trailovic Stefan Trailovic - 3 months ago 11
CSS Question

Sibling css selector not changing

All

tr
with ID 1 and all under them, before ID 2 should be the same color. Check the example. But it will not change after ID 2.

This is my code:



[id="1"], [id="1"] ~ tr {
background-color: blue;
}
[id="2"], [id="2"] ~ tr {
background-color: red;
}

<table>
<tbody>
<tr id="1"><td>foo</td></tr> <!-- Blue -->
<tr><td>foo</td></tr> <!-- Blue -->
<tr><td>foo</td></tr> <!-- Blue -->
<tr id="2"><td>foo</td></tr> <!-- Red -->
<tr><td>foo</td></tr> <!-- Red -->
<tr id="1"><td>foo</td></tr> <!-- Blue (But is Red) -->
<tr><td>foo</td></tr> <!-- Blue (But is Red) -->
<tr><td>foo</td></tr> <!-- Blue (But is Red) -->
<tr><td>foo</td></tr> <!-- Blue (But is Red) -->
</tbody>
</table>




Answer

Given html at Question you can use adjacent sibling selector +, !important

[class="1"],
[class="1"] ~ tr {
  background-color: blue;
}

[class="2"],
[class="2"] + tr {
  background-color: red !important;
}
<table>
  <tbody>
    <tr class="1">
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr class="2">
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr class="1">
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
  </tbody>
</table>


alternatively, using jQuery's .nextUntil(), .add()

$(".1").nextUntil(".2").add(".1").addClass("blue");
$(".2").nextUntil(".blue").add(".2").addClass("red");
.blue {
  background-color: blue;
}

.red {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <tbody>
    <tr class="1">
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr class="2">
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr class="1">
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
    <tr>
      <td>foo</td>
    </tr>
  </tbody>
</table>

Comments