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>
.bar ~ div:nth-of-type(-n+3)
means:
:nth-of-type(-n+3)
: select every element which is among the first three of its type inside its parentdiv
: restrict to div
elements only.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With