Using the last-child selector
My goal is to apply the CSS on the last li
, but it doesn't do that.
#refundReasonMenu #nav li:last-child {
border-bottom: 1px solid #b5b5b5;
}
<div id="refundReasonMenu">
<ul id="nav">
<li><a id="abc" href="#">abcde</a></li>
<li><a id="def" href="#">xyz</a></li>
</ul>
</div>
How can I select only the last child?
The :last-child
pseudoclass still cannot be reliably used across browsers. In particular, Internet Explorer versions < 9, and Safari < 3.2 definitely don't support it, although Internet Explorer 7 and Safari 3.2 do support :first-child
, curiously.
Your best bet is to explicitly add a last-child
(or similar) class to that item, and apply li.last-child
instead.
Another solution that might work for you is to reverse the relationship. So you would set the border for all list items. You would then use first-child to eliminate the border for the first item. The first-child is statically supported in all browsers (meaning it can't be added dynamically through other code, but first-child is a CSS2 selector, whereas last-child was added in the CSS3 specification)
Note: This only works the way you intended if you only have 2 items in the list like your example. Any 3rd item and on will have borders applied to them.
If you think you can use Javascript, then since jQuery support last-child
, you can use jQuery's css method and the good thing it will support almost all the browsers
Example Code:
$(function(){
$("#nav li:last-child").css("border-bottom","1px solid #b5b5b5")
})
You can find more info about here : http://api.jquery.com/css/#css2
If the number of list items is fixed you can use the adjacent selector, e.g. if you only have three <li>
elements, you can select the last <li>
with:
li+li+li {
color: red;
font-size: 170%;
}
<ul>
<li>First</li>
<li>Second</li>
<li>Last</li>
</ul>