Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nth-of-type selector combined with sibling selector

I'm confused on how the nth-of-type selector works in conjunction with the sibling selector. In the example below, I'd expect squares 3, 4, and 5 to be red, but they aren't. How does the .bar ~ div:nth-of-type(-n+3) selector below select elements?

If I wanted to get the first three elements after .bar what would be the proper selector to do that?

.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>
like image 207
JKillian Avatar asked Mar 15 '23 08:03

JKillian


1 Answers

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

  1. :nth-of-type(-n+3): select every element which is among the first three of its type inside its parent
  2. div: restrict to div elements only
  3. .bar ~: restrict to elements which have a previous sibling (not necessarily immediately) with the class bar.

Since any of the following siblings of .bar isn't among the three first div elements, the selector doesn't match anything.

If you want to get the three .foo elements immediately after .bar, you can use:

.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>
like image 175
Oriol Avatar answered Apr 25 '23 17:04

Oriol