CSS: first child, last child, only child selectors
No sibling
tag:only-child-
match element x if:
- tag matches x.
- x has no siblings.
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).
Match by specific sibling rank
First child, last child
tag:first-child-
match element x if:
- tag matches x.
- x is the first child.
/* Match span only when it is the 1st child. Note, this is different from “match the 1st span”. */ span:first-child { color: red; } tag:last-child-
Match tag only if it is the last child element.
Nth-child
Nth-last-child
tag:nth-last-child(arg)-
similar to
:nth-child, but count starting from end.
Nth-of-type
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 child.
CSS selectors by child or sibling rank
CSS. Selectors
Selector types
Simple selectors
- CSS: type selector (tag name)
- CSS: universal selector (* any tag)
- CSS: class selector (.x)
- CSS: ID selector (#)
- CSS: attribute selector ([x])
Combinators
- CSS: descendant selector (space)
- CSS: child selector (>)
- CSS: adjacent sibling selector (+)
- CSS: subsequent sibling selector (~)
Selector list
Nesting syntax
Special selector
- CSS: :root selector
- CSS: no child selector
- CSS: first child, last child, only child selectors
- CSS: nth-child selector
- CSS: nth-child arg of selector
- CSS: nth-of-type selector
- CSS: pseudo-class selector (:)
- CSS: pseudo-element selector (::)
- CSS: negation selector (:not)
- CSS: :has descendant selector