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 :nth-last-child(n) selector matches every element that is the nth child, regardless of type, of its parent, counting from the last child. n can be a number, a keyword, or a formula.
The :last-child selector is a pseudo-class that allows you to target an element that is the last child element within its parent. See also :first-child, :nth-child, :nth-last_child, and :only-child selectors.
The :last-child selector allows you to target the last element directly inside its containing element. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling content.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With