It seems to me that nth-of-type only works within the same parent element. Is there any way to get it work across the whole page?
My situation: I would like to cycle through five hover colors for links. These links are scattered across many paragraphs. Since there are only one or two links per paragraph, the first couple of hover colors are disproportionately favored.
Thanks!
As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .
The :nth-of-type(n) selector matches every element that is the nth child, of the same type (tag name), of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-child() selector to select the element that is the nth child, regardless of type, of its parent.
Definition and Usage The :nth-last-of-type(n) selector matches every element that is the nth child, of a particular type, of its parent, counting from the last child. n can be a number, a keyword, or a formula.
There cannot be a way to select :nth-of-type() of a class, because :nth-of-type() only selects the nth child of its type.
nth-of-type always looks at the element's index relative to it's direct parent: (w3schools), so it won't work across the whole page.
Your best bet is to implement this behaviour with javascript, here's a quick demo using JQuery: jsfiddle
var styles = ["first", "second", "third"];
var index = 0;
$("body").find("a").each(function() {
$(this).addClass(styles[index++]);
if (index >= styles.length) index = 0;
});
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