Nth-of-type selector combined with selector

I am confused about how the selector nth-of-typeworks in conjunction with the selector. In the example below, I would expect squares 3, 4, and 5 to be red, but that is not the case. How to select a selector .bar ~ div:nth-of-type(-n+3)to select items?

If I wanted to get the first three elements after .bar, what would be the right selector for this?

.foo {
  background-color: blue;
  color: white;
  width: 50px;
  height: 50px;
  display: inline-block;
  border: solid 1px black;
}
.bar {
  background: green;
}
.bar ~ div {
  background-color: orange;
}
.bar ~ div:nth-of-type(-n+3) {
  background-color: red;
}
<div>
  <div class="foo">0</div>
  <div class="foo">1</div>
  <div class="foo bar">2</div>
  <div class="foo">3</div>
  <div class="foo">4</div>
  <div class="foo">5</div>
  <div class="foo">6</div>
  <div class="foo">7</div>
</div>
Run codeHide result
+4
source share
1 answer

.bar ~ div:nth-of-type(-n+3) means:

  • :nth-of-type(-n+3): select each element that is among the first three of its types inside the parent
  • div: restrict only to divelements
  • .bar ~: restrict the elements that have the previous sibling (not necessarily immediately) with the class bar.

.bar div, .

.foo .bar, :

.bar + .foo, .bar + .foo + .foo, .bar + .foo + .foo + .foo

.foo {
  background-color: blue;
  color: white;
  width: 50px;
  height: 50px;
  display: inline-block;
  border: solid 1px black;
}
.bar {
  background: green;
}
.bar ~ div {
  background-color: orange;
}
.bar + .foo, .bar + .foo + .foo, .bar + .foo + .foo + .foo {
  background-color: red;
}
<div>
  <div class="foo">0</div>
  <div class="foo">1</div>
  <div class="foo bar">2</div>
  <div class="foo">3</div>
  <div class="foo">4</div>
  <div class="foo">5</div>
  <div class="foo">6</div>
  <div class="foo">7</div>
</div>
Hide result
+6

Source: https://habr.com/ru/post/1613398/