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.
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 {}
You want the :first-child
and :last-child
pseudo-class selectors:
<style type="text/css">
.menu ul li:first-child a {
color: green;
}
.menu ul li:last-child a {
color: red;
}
</style>
<div class="menu">
<ul>
<li><a href="#">apple</a></li>
<li><a href="#">baker</a></li>
<li><a href="#">charlie</a></li>
<li><a href="#">delta</a></li>
</ul>
</div>
What I think you require are the :first-child and :last-child selectors.
.menu ul li:first-child a
.menu ul li:last-child a