CSS: nth-of-type selector
First-of-type, last-of-type
tag:first-of-type-
match element x if:
- tag matches x.
- of all x's siblings, consider only those matched by tag, x is the first.
tag is optional. It can be a simple selector (selecting by tag name, id, class etc) or a compound selector (combination of tag name, id, class etc). If empty, it means the universal selector (* any tag).
p:first-of-type { color: red; } <div> <div> Zs3vx </div> <p>aa ✅</p> <p>bb</p> <div> <p class="xx">cc ✅</p> <p class="xx">dd</p> </div> <p>ee. no match here because p is not first child.</p> </div> tag:last-of-type-
similar to
:first-of-typebut match last.
Nth-of-type, nth-last-of-type
tag:nth-of-type(arg)-
equivalent to
tag:nth-last-of-type(arg)-
similar to
:nth-of-typebut counting starting from end.
Match unique child among siblings
tag:only-of-type-
Match tag if it is the only type (tag name) among siblings.
span:only-of-type { color: red; } <div> <div>1</div> <span>2</span> <span>3</span> </div> <div> <div>A</div> <span>B</span> <div>C</div> </div> In the above example, only the B will be colored, because that span is the only span tag among siblings.
2013-08-18 thanks to Brennan Young for correction on nth-of-type.