I've got the following html:
<ul class="menu">
<li><a>list item 1</a></li>
<li><a>list item 2</a></li>
...
<li><a>list item 5</a></li>
</ul>
I want to apply a border to all the <a>
elements except the last one.
I've been trying this:
.menu a {
border-right: 1px dotted #ccc;
}
.menu a:last-of-type {
border-right: none;
}
but I end up with a border on none of the elements, I guess because the <a>
in each case is the last of type.
How can I do this? I'd prefer to use only CSS if possible, and I'd like IE9 compatibility if possible.
When designing and developing web applications, sometimes we need to select all the child elements of an element except the last element. To select all the children of an element except the last child, use :not and :last-child pseudo classes.
The :not() selector excludes the element passed to it from selection. The :last-child selector selects the last child.
Approach: Use the :not(selector), also known as negation pseudo-class which takes a simple selector as an argument and allows you to style all the elements except the element specified by the selector.
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.
Change:
.menu a:last-of-type {
border-right: none;
}
to:
.menu li:last-of-type a {
border-right: none;
}
.menu a {
border-right: 1px dotted #ccc;
}
.menu li:last-of-type a {
border-right: none;
}
<ul class="menu">
<li><a>list item 1</a></li>
<li><a>list item 2</a></li>
<li><a>list item 3</a></li>
<li><a>list item 4</a></li>
<li><a>list item 5</a></li>
</ul>
As you surmised, the rule you were using was targeting every a
because it was the last child within each li
. Just move the :last-of-type
to the li
instead.
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