CSS: first child, sibling rank selector
No Sibling
tag:only-child-
Match tag if it's the only child.
tag here is compound selector, or none, which means the universal selector (* any tag).
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(arg)tag:nth-last-child(arg)-
similar to
:nth-child, but count starting from end.
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.
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(arg)-
equivalent to
:nth-child(arg of tag) tag:nth-last-of-type(arg)-
similar to
:nth-of-type, but counting starting from end.
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 sibling criteria
CSS, Selectors
Selector types
- CSS: types of selectors
- CSS: simple selectors
- CSS: compound selectors
- CSS: complex selector (combinator)
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
Special selector
- CSS: :root selector
- CSS: no child selector
- CSS: first child, sibling rank selector
- CSS: nth-child selector
- CSS: pseudo-class selector (:)
- CSS: pseudo-element selector (::)
- CSS: negation selector (:not)
- CSS: “is any of” selector (:is, :where)
- CSS: :has descendant selector