
A pseudo-class matches an element based on its state or its place in the document. A pseudo-element targets a part of an element, such as the first line of a paragraph.
13. CSS pseudo-classes and pseudo-elements
13.1. Select elements by their position
:first-childand:last-childmatch the first and last element children of a parent.:nth-child(2n)matches even positions among element siblings.:nth-last-child(2)counts backward from the end.:first-of-typeand:last-of-typecount siblings with the same tag name.:nth-of-type(odd)matches alternate siblings of that tag name.:only-childmatches when an element has no element siblings.:only-of-typematches when it has no sibling of the same type.
li:nth-child(even) { background: #e8f1fb; }
p:first-of-type { font-weight: bold; }Open structural selector example 1
Open structural selector example 2
Open structural selector example 3
13.2. Select elements by state
:hover responds to a pointing device. :active matches while an element is being activated. :focus matches when an element has focus and :focus-visible helps show focus according to the browser’s input heuristics. Keep the focus indicator easy to see for keyboard users.
:link matches unvisited links and :visited matches visited links. Browsers restrict the properties you can change with :visited to protect browsing history. Place common link rules in the order :link, :visited, :hover, :active when they otherwise have equal precedence.
a:link { color: #15548a; }
a:visited { color: #643c84; }
a:hover { text-decoration-thickness: 0.15em; }
a:active { color: #862623; }
a:focus-visible { outline: 2px solid currentColor; outline-offset: 3px; }13.3. Style parts of an element
::first-linestyles the first formatted line of text, which can change when a block resizes.::first-letterstyles the first letter of an eligible block.::beforeand::aftergenerate content immediately before or after an element’s content. Keep essential information in the HTML.::selectioncan style highlighted text within the selected content.
p::first-line { color: darkgreen; }
h2::first-letter { color: navy; }
.note::before { content: "✦ "; }
.note::after { content: " ✦"; }
p::selection { color: white; background: #4b3157; }Try the pseudo-element example
Try it yourself
How do you style the first line of each paragraph?
Use p::first-line. To target the first paragraph among siblings of type p, use p:first-of-type.