Laura Sage Laura Sage - 3 months ago 8
CSS Question

Automatically style each link on a page differently using nth-child/type?

I want to add a special style to specific links on my page but I don't want to add a separate class to each link that might appear on a page. I want every 8n+1 (through 8n+8) href to be a different color. So far it's not working using nth-child or nth-of-type. I assume this is because the links are in paragraphs and lists, etc., so they aren't recognized as direct or even sibling selectors, even though the parent selector I'm prefixing it with is the parent.

Here's my CSS:

#main > a:nth-of-type(8n+1) {
color: #ef9623 !important;
}

#main > a:nth-of-type(8n+2) {
color: #dab828 !important;
}


etc. I've tried it with ~ and without either one. None of them seem to work. Is it likely that this will require jquery instead of CSS?

Answer

If the links are in paragraphs, than the css selectors need to appropriate. Assuming you have this html:

<div class="wrap">
    <p><a href="#">foo</a></p>
    .
    .
    .
</div>

To style the links you need to select like this:

div.wrap p:nth-child(8n+2)  a { … }

Because the paragraphs are the children to count.

EDIT If some of the links are in paragraphs and some not, you need to create a more flexible selector. One thing you can do is to set a class for each child of the first level like:

<div class="wrap">
    <p class="countable"><a href="#">foo</a></p>
    <div class="countable"><a … </a></div
    .
    .
    .
</div>

Than you can select like: div.wrap .countable:nth-child(…) a { … }

I am unsure if even: div.wrap > *:nth-child(…) a { … } could work, but I am pretty sure…

PROOF

EDIT #2

In fact the nth-child pseudo selector will only work for direct children (>), to style each 8th link, no matter where in the HTML you will need to use JS.

$(document).ready(function () {
    $.each($('#main a'), function (idx, e) {
        // % the nth child 
        if (idx % 8 == 0) { 
            //do something with the element
            $(e).html('eighth');
        }
    });
});

This way each link, in appearance in the DOM, will be added to a list and styled if idx % nthChild == 0.