This example provides the desired outcome of selecting the first, second, and third child elements that are of class "subhead". However, my question is, Is there any selection method that will select the first, second, and third occurrences of class "subhead" irregardless of its exact child position in the parent, such that this would work when it is not known in advance what those positions will be; and we could use postions 1,2,3 instead of 1,3,5 since it won't known how many sibling elements will be between each subhead?
Thank you.
div.scrl_can * {
height:25px;
border: 1px solid black;
}
.subhead:nth-of-type(1) {
background-color: blue;
}
.subhead:nth-of-type(3) {
background-color: green;
}
.subhead:nth-of-type(5) {
background-color: yellow;
}
<div id="main">
<div>
<div>
<div class="scrl_can">
<div class="subhead"></div>
<div></div>
<div class="subhead"></div>
<div></div>
<div class="subhead"></div>
<div></div>
</div>
</div>
</div>
</div>
You can use the of selector
syntax of nth-child
:
div.scrl_can * {
height:25px;
border: 1px solid black;
}
.subhead:nth-child(1 of .subhead) {
background-color: blue;
}
.subhead:nth-child(2 of .subhead) {
background-color: green;
}
.subhead:nth-child(3 of .subhead) {
background-color: yellow;
}
<div id="main">
<div>
<div>
<div class="scrl_can">
<div class="subhead"></div>
<div></div>
<div></div>
<div></div>
<div class="subhead"></div>
<div></div>
<div></div>
<div class="subhead"></div>
<div></div>
</div>
</div>
</div>
</div>