CSS: first child, last child, only child selectors

By Xah Lee. Date: . Last updated: .

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
Combinators
Selector list
Nesting syntax
Special selector
Misc