I’ve got a dom structure which is generated by a JS framework and may looks like this:
span:nth-child(odd) { background-color: lightblue; }
span {
display: block;
}
<div id="parent">
<div class="child">
<span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
<span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
</div>
<div class="child">
<span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
</div>
<div class="child">
<span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
<span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
<span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
</div>
<div class="child">
<span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
<span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
<span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
<span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
<span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
<span>Some text to color in alternate colors with the previous span no matter if it's the same parent or not</span>
</div>
<div class="child">
<span>Some text to color in alternate colors</span>
</div>
</div>
I’m trying to color the span alternatively no matter if the parent is the same or not.
I gave it a try with pseudo selectors and this question CSS div alternating colour, with no luck. Is this achievable with CSS only or should I dig into a JS framework solution based?
2
Answers
}
instead of using
nth-child
, we can usediv:nth-of-type(odd)
I doubt there’s a cross-browser CSS-only solution so I recommend using a little bit of Javascript.
Using the
querySelectorAll()
of the Document interface we can get a list of elements matching the query requested by a selector passed to the function.So if we want all
<span>
elements:If we now go further and transform the returned
HTMLCollection
into an array, we can filter out the even or odd elements and add a CSS class using theelement.classList.add()
function.