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
704 views
in Technique[技术] by (71.8m points)

html - Target the first and last anchor in an unordered list's list item

I'm trying to target the first and last anchor within a list-item of an unordered list:

<ul>
    <li><a href="#">HOME</a></li>
    <li><a href="#">LINK</a></li>
    <li><a href="#">LINK</a></li>
    <li><a href="#">LINK</a></li>
    <li><a href="#">LINK</a></li>
</ul>

I have tried:

.menu ul .last a {}
.menu ul.last a {}
.menu ul li .last a {}
.menu ul li.last a {}

I need to target the anchor as I need to remove the border of the first and last anchor. I can't use (or at least I don't think I can) border on the <li>, as it needs some vertical padding so the separator border is not vertically flush.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you don't need to worry about old browsers, use the :first-child and :last-child pseudo-classes on the list items, like so:

/* Because we are looking at the <li> children of your <ul> */
.menu ul li:first-child a {}
.menu ul li:last-child a {}

However, support for CSS3 :last-child is pretty poor right now, so a more browser-compatible alternative is to manually give the last list item a last class, like so (and doing the same for first):

<ul>
    <li class="first"><a href="#">HOME</a></li>
    <li><a href="#">LINK</a></li>
    <li><a href="#">LINK</a></li>
    <li><a href="#">LINK</a></li>
    <li class="last"><a href="#">LINK</a></li>
</ul>

Then, you can use these selectors:

.menu ul li.first a {}
.menu ul li.last a {}

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

...