Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

css - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...