Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS3 nth-of-type across the entire page?

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!

like image 978
Joyce Avatar asked Jun 18 '13 02:06

Joyce


People also ask

What's the difference between the nth-of-type () and Nth child () selector?

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 .

How do you use the nth element using the CSS selector?

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.

How do you find the nth last of a type?

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.

Can I use nth-of-type with class?

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.


1 Answers

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;
});
like image 86
Jeremy Ninnes Avatar answered Oct 20 '22 13:10

Jeremy Ninnes