How to I target all these anchors with css3?

<div class="answer">
	<h3>words</h3>
	<a href="" target="_blank">PDF</a>
	<a href="" target="_blank">DOC</a>
	<a href="" target="_blank">WEB</a>
	<h3>words2</h3>
        <a href="" target="_blank">PDF</a>
	<a href="" target="_blank">DOC</a>
	<a href="" target="_blank">WEB</a>
       <h3>words</h3>
	<a href="" target="_blank">PDF</a>
	<a href="" target="_blank">DOC</a>
	<a href="" target="_blank">WEB</a>
	<h3>words2</h3>
        <a href="" target="_blank">PDF</a>
	<a href="" target="_blank">DOC</a>
	<a href="" target="_blank">WEB</a>
</div>

The pdf anchor needs a pdf background image. The word doc needs that background image. And the web version needs that background image. So three different images targeted to the exact same anchors in the exact same order repeated about 30 times. Im assuming nth-child but I cant seem to get it to work.

Skipping the obvious questions about modifying the HTML, you could do this:

a:nth-of-type(3n+1) {color: red;}
a:nth-of-type(3n+2) {color: blue;}
a:nth-of-type(3n+3) {color: green;}

nth-child doesn’t work here, because the h3s are children of the same parent too, which messes things up, so nth-of-type is the way to focus just on the anchors.

1 Like

thanks ralphm. Im assuming I’d have to continue on with that 3n+4, 3n+5 and etc. Any way to say those rules only tree times and have them repeat to every 3 anchors? While skipping over the h3 of course

Yes, with the current HTML structure.

If you did something like wrap a div around each group of three links, this would be all you’d need:

a:nth-child(1) {color: red;}
a:nth-child(2) {color: blue;}
a:nth-child(3) {color: green;}

Mind you, you don’t even need CSS3 for this. This alone would work for all instances in your original HTML:

h3 + a {color: red;}
h3 + a + a {color: blue;}
h3 + a + a + a {color: green;}
2 Likes

Are you SURE you’re always going to have all three types of docs? Or will you only sometimes have one or two?
If you’re not 100% sure, it seems to me that just adding an appropriate class to each link might be a more bulletproof approach to this.

1 Like

yeah positive it will always be 3 docs (the anchors) preceded by the single h3. Yeah I would do classes too if the css is going to have to get all crazy like that. Im just hoping there was a css3 way to target each anchor and repeated 30 times.

oh ok right thats not too crazy. I like that!

Hi,

assuming your are linking directly to the given files (e.g. your href eds width *.pdf) you can also style the links based on their respective href-value.

a[href$=".pdf"] {
    color: red;
}

This would style every a-element with a href-value that ends with “.pdf”. This has the advantage that your styling wouldn‘t be dependend on source-order. Browser support is pretty decent, too.

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.