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).

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.