CSS: Selector: Match Sibling

By Xah Lee. Date: . Last updated: .

Subsequent-Sibling Combinator (Has Older Brother X)

aaa ~ bbb

Match all bbb that has a older brother aaa.

Each expression can be compound selector, e.g. div.xyz.

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

Next-Sibling Combinator (Has Immediate Older Brother X)

aaa + bbb

Match any bbb that immediately comes after aaa. (aaa and bbb are in the same level.)

Each expression can be compound selector, e.g. div.xyz.

/* match the b tag that comes immediately after span */
span+b {color:red;}

matches the B:

<div>
<span>A</span>
<b>B</b>
</div>

No Sibling

tag:only-child

Match tag if it's the only child.

Match by Specific Sibling Rank

tag:first-child

Match tag only if it is the 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:last-child

Match tag only if it is the last child element.

tag:nth-child(n)

Match tag only if it is nth child element.

(counting start at 1. Cannot be negative.)

tag:nth-last-child(n)

count from right, starting at 1.

Match by Specific Order Rank of Same Tag in Siblings

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

tag:first-of-type

Match tag if it is the first occurrence of tag among siblings.

Each expression can be compound selector, e.g. div.xyz.

p:first-of-type {
color:red;
}

this match the aa and cc in the following

<div>

<p> aa </p>
<p> bb </p>

<div>
<p class="xx"> cc </p>
<p class="xx"> dd </p>
</div>

<p> ee </p>

</div>
tag:last-of-type

Match tag that is last occurrence of tag among siblings.

tag:nth-of-type(n)

Match tag that is nth occurrence of the same tag among siblings.

Count starts at 1.

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

Match tag that is nth occurrence of the same tag among siblings, counting from right.

Match Unique Child in 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>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