CSS: Selector: Match Relation to Sibling

By Xah Lee. Date: . Last updated: .

No Siblings

tag:only-child

Match tag if it's the only child.

Match Sibling Structure

These allow you to check if a element comes after another. Immediate, or not.

expr1 + expr2
(this is called Next-sibling combinator)

Match any expr2 that immediately comes after expr1. (expr1 and expr2 are in the same level.)

Each of the expr can be compound selector, such as CSS: Selector: Match Attribute Name or Value

span+b {color:red;}

matches the B:

<div>
<span>A</span>
<b>B</b>
</div>
expr1 ~ expr2
(this is called Subsequent-sibling combinator)

Match all expr2 that is a sibling of expr1 and comes after expr1.

Each of the expr can be compound selector, such as CSS: Selector: Match Attribute Name or Value

/* make list items red, except first */
li ~ li {color:red;}

Match by Order in Siblings

tag:first-child

Match tag only if it is first child element.

/*
Match span only when it is the 1st child.
Note, this is different from “match the 1st span”.
*/
span:first-child {color:red;}
tag:nth-child(n)

Match tag only if it is nth child element. (counting start at 1. Cannot be negative.)

tag:last-child

same as tag:nth-last-child(1)

tag:nth-last-child(n)

count from right, starting at 1.

Match by Order of Same Tag in Siblings

These let you select the nth occurrence of the tag. (counting only those at the same level children)

tag:nth-of-type(n)

Match tag that is nth occurrence of the same tag. Count starts at 1.

tag:nth-last-of-type(n)

same as tag:nth-of-type(n) but counting from right.

tag:first-of-type

same as tag:nth-of-type(1)

tag:last-of-type

same as tag:first-of-type but the last.

tag:only-of-type

Match tag if it is the only type (tag name) among siblings.

span:only-of-type {color:red;}
<div>
 <div>11</div>
 <span>22</span>
 <span>33</span>
</div>
<div>
 <div>AA</div>
 <span>BB</span>
 <div>CC</div>
</div>

In the above example, only the BB 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