Reputation: 483
I have a HTML document with the abbreviated HTML content:
<div class="list">
<form name="signupForm">
<label class="item item-input">
<input>
</label>
<label class="item item-input">
<input>
</label>
<label class="item item-input">
<input>
</label>
<label class="item item-input">
<input>
</label>
<label class="item item-button">
<input class="button button-block button-positive">
</label>
<label class="item item-button">
<input class="button button-block button-signup">
</label>
</form>
</div>
My expected behavior is that the CSS selector .item.item-input:last-of-type
will grab the 4th label
element and the last .item.item-input
element of the form
parent.
What am I doing wrong?
Upvotes: 14
Views: 12603
Reputation:
:last-of-type
matches an element which is the last element of its type (tag) within its (first-level) parent, period. It doesn't know or care about what other selectors you may have combined, including class selectors such as .item-input
, or anything else.
There is no straightforward way in CSS to accomplish what you want, which could be expressed as :last-of-selector
. Some alternatives that have been suggested include
Wrap the first four elements in a separate div, so you can do :last-of-type
within it.
Have somebody (server, local JS) mark the element you want with a specific class, and refer to it.
Other hacks, such as hard-wiring the number of extra elements at the end that you want to skip, and use :nth-last-of-type
.
Give the elements in question a different tag, if you can so manage, and then you can use last-of-type
.
Upvotes: 15
Reputation: 78676
Finding the .class:last-of-type
is not possible. The :last-of-type
CSS pseudo-class represents the last sibling with the given element name in the list of children of its parent element. The correct syntax is element:last-of-type
You might be interested in :nth-last-of-type(n)
, you could then use the following selector to target that element.
label:nth-last-of-type(3) { style properties }
The :nth-last-of-type(n)
selector matches every element that is the nth child, of a particular type, of its parent, counting from the last child.
However, you'll need to use Javascript if you can't edit the markup and the number of items isn't fixed.
Upvotes: 1
Reputation: 4564
Apparently :last-of-type
(from the MDN Docs) can only be used with namespace and type selectors (tag name selectors like input
).
I suggest changing your HTML structure to wrap the .item-input
elements in a <div>
. Alternatively, I have also seen a .last
class manually added to substitute the pseudo-selector.
Upvotes: 3