To select the last element of a specific class, you can use the CSS :last-of-type pseudo-class.
The CSS child selector has two selectors separated by a > symbol. The first selector indicates the parent element. The second selector indicates the child element CSS will style.
This can be done using an attribute selector.
[class~='list']:last-of-type {
background: #000;
}
The class~
selects a specific whole word. This allows your list item to have multiple classes if need be, in various order. It'll still find the exact class "list" and apply the style to the last one.
See a working example here: http://codepen.io/chasebank/pen/ZYyeab
Read more on attribute selectors:
http://css-tricks.com/attribute-selectors/ http://www.w3schools.com/css/css_attribute_selectors.asp
You can use the adjacent sibling selector to achieve something similar, that might help.
.list-item.other-class + .list-item:not(.other-class)
Will effectively target the immediately following element after the last element with the class other-class
.
Read more here: https://css-tricks.com/almanac/selectors/a/adjacent-sibling/
This is a cheeky answer, but if you are constrained to CSS only and able to reverse your items in the DOM, it might be worth considering. It relies on the fact that while there is no selector for the last element of a specific class, it is actually possible to style the first. The trick is to then use flexbox to display the elements in reverse order.
ul {
display: flex;
flex-direction: column-reverse;
}
/* Apply desired style to all matching elements. */
ul > li.list {
background-color: #888;
}
/* Using a more specific selector, "unstyle" elements which are not the first. */
ul > li.list ~ li.list {
background-color: inherit;
}
<ul>
<li class="list">0</li>
<li>1</li>
<li class="list">2</li>
</ul>
<ul>
<li>0</li>
<li class="list">1</li>
<li class="list">2</li>
<li>3</li>
</ul>
You can't target the last instance of the class name in your list without JS.
However, you may not be entirely out-of-css-luck, depending on what you are wanting to achieve. For example, by using the next sibling selector, I have added a visual divider after the last of your .list
elements here: http://jsbin.com/vejixisudo/edit?html,css,output
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