Select Second Child

I am trying to use this to select the second a tag from a list:

.container li a:first-child + a { ... }

but it doesn't seem to work. Is there another, ideally pure CSS way (other than a:nth-child(2)) or can anyone see where I have gone wrong?

2

4 Answers

Make sure your <li> actually has two <a> elements as its first two children, and not some other elements around them since those may be invalidating the :first-child and adjacent sibling selectors.

If you just want to select the second <a> element regardless of what other types of elements there are in your <li>, use this selector:

.container li a:nth-of-type(2)

If your <li> will only have exactly 2 <a> elements, you can use the general sibling combinator ~ for bonus IE7/IE8 support:

.container li a ~ a

Or did you mean to find the <a> element in the second <li> rather than the second <a> element in a <li> (since "list" probably refers to <ul> or <ol> here)? If so, you'll want either of these selectors:

.container li:first-child + li a
.container li:nth-child(2) a
3

I suspect your anchors are within list items:

<ul class="container">
    <li><a href="">...</a></li>
    <li><a href="">...</a></li>
    <li><a href="">...</a></li>
</ul>

In that case, you have to rewrite the style to:

.container li:first-child + li a { ... } 
0

Just use :nth-of-type:

.container li a:nth-of-type(2) {
    /* ... */
}

The problem here is probably that the first <a> is not the first child, or the second <a> is not adjacent to it. Regardless, :nth-of-type is the right way to do it.


If you have one <a> per <li>, then you probably mean .container li:nth-of-type(2) a.

Use nth-child(2)

.container li a:nth-child(2){....}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins

Sarah Jenkins

Senior Technology Editor & AI Specialist

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.

Share this article
Twitter Facebook Pinterest