Lesson 10
18 min
Target specific states and parts of elements with :hover, :nth-child, ::before and ::after.
Definition
A pseudo-class is a keyword added to a selector, preceded by a single colon, that targets an element based on its state or itsposition. A pseudo-element, preceded by two colons, targets a part of an element or inserts content generated by CSS. In both cases, you style things without having to modify the HTML.
A pseudo-class (prefixed with :) targets an element in a particular state, without it needing a dedicated HTML class.
a:hover {
color: #6d28d9; /* when the mouse hovers over it */
}
button:active {
transform: scale(0.97); /* while being clicked */
}
input:focus {
border-color: #6d28d9; /* when the field is active/selected */
}
button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
input:checked + label {
font-weight: bold; /* the checkbox right before it is checked */
}:hover — when the mouse hovers over the element.:focus — when the element has keyboard/mouse focus (a form field, for example).:active — during the moment of the click.:disabled — a disabled form element.:checked — a checked checkbox or radio button.The :focus pseudo-class applies as soon as an element receives focus, even after a simple mouse click, which can make outlines appear on buttons where they’re sometimes unwanted. :focus-visible only applies when the browser judges that the indicator is useful, typically during keyboard navigation. It’s the best choice for balancing aesthetics and accessibility.
button:focus {
outline: none; /* avoid on its own: removes the indicator for everyone */
}
button:focus-visible {
outline: 3px solid #6d28d9; /* visible only for keyboard navigation */
outline-offset: 2px;
}Never remove focus without a replacement
Removing the focus indicator without providing another one makes a site unusable for people who navigate with the keyboard. If you hide outline, always define a visible style again with :focus-visible.
A link has two basic states: :link for a link that has never been visited and:visited for a link that has already been opened. For all the states to work without conflict, you declare them in a specific order, remembered by the abbreviationLVHA (Link, Visited, Hover, Active), because rules of equal specificity are settled by their order in the file.
a:link { color: #6d28d9; } /* never visited */
a:visited { color: #7e22ce; } /* already visited */
a:hover { color: #4c1d95; text-decoration: underline; }
a:active { color: #2e1065; } /* while being clicked */Forms have dedicated pseudo-classes that reflect their HTML validation: you can display a correct field in green and an erroneous one in red without writing a single line of JavaScript. Keep in mind that :invalid applies from the moment the page loads, even before the user has typed anything; :user-invalid waits until the user has interacted with the field.
input:required {
border-left: 4px solid #6d28d9; /* required field */
}
input:valid {
border-color: #15803d; /* content is valid (a valid email, etc.) */
}
input:invalid {
border-color: #b91c1c; /* content is not valid */
}
input:placeholder-shown {
background-color: #f8fafc; /* field still empty, sample text displayed */
}Other pseudo-classes target an element based on its position among its siblings, very useful for styling lists without adding extra HTML classes.
li:first-child {
font-weight: bold; /* the first item in the list */
}
li:last-child {
border-bottom: none; /* the last item */
}
tr:nth-child(even) {
background-color: #f8fafc; /* every other row, for a "striped" table */
}
tr:nth-child(odd) {
background-color: white;
}
li:nth-child(3) {
color: red; /* exactly the 3rd item */
}
p:not(.intro) {
color: gray; /* all <p> elements EXCEPT those with the .intro class */
}:first-child / :last-child — first/last element among its siblings.:nth-child(even/odd/n) — selects based on a position or a pattern (very useful for striped tables).:not(selector) — excludes elements that match the given selector.:nth-child() accepts a formula of the form an + b, where n takes the successive values 0, 1, 2, 3... This lets you target regular patterns: every third element, the first five, all except the first two. There are also handy relatives like :only-child, :nth-of-type() and :empty.
li:nth-child(2n + 1) { } /* items 1, 3, 5...: equivalent to odd */
li:nth-child(3n) { } /* items 3, 6, 9...: one out of three */
li:nth-child(-n + 3) { } /* only the first 3 */
li:nth-child(n + 4) { } /* all from the 4th onward */
li:only-child { } /* the only child of its parent */
p:nth-of-type(2) { } /* the 2nd paragraph, counting only <p> elements */
div:empty { display: none; } /* elements with no content at all */These three “functional” pseudo-classes simplify selectors that would otherwise be long and repetitive. :is() groups several selectors; :where() does the same thing but with zero specificity, so it’s easy to override; :has() selects a parent based on what it contains, which wasn’t possible in CSS before.
/* Without :is(), you'd have to repeat ".card" three times */
.card :is(h2, h3, h4) {
color: #4c1d95;
}
/* Like :is(), but adds no specificity */
:where(ul, ol) {
padding-left: 1.5rem;
}
/* A card that contains an image gets a border */
.card:has(img) {
border: 2px solid #ddd6fe;
}
/* A form field whose input is invalid */
.field:has(input:invalid) {
background-color: #fef2f2;
}A pseudo-element (prefixed with ::) targets a specific part of an element, or lets you insert content generated by CSS without touching the HTML.
p::first-line {
font-weight: bold; /* only the first line of the paragraph */
}
p::first-letter {
font-size: 2em; /* the first letter, larger (a "drop cap" effect) */
}
.quote::before {
content: "“";
color: #6d28d9;
}
.quote::after {
content: "”";
color: #6d28d9;
}
::selection {
background-color: #ddd6fe; /* color of the text highlighted by the user */
}::before / ::after — insert generated content before/after the element, via the mandatory content property.Two very handy pseudo-elements target parts that HTML doesn’t expose:::marker for a list’s bullet or number, and ::placeholder for the sample text of a form field.
li::marker {
color: #6d28d9; /* purple bullets without touching the list text */
font-weight: bold;
}
input::placeholder {
color: #94a3b8; /* more subtle hint text */
font-style: italic;
}A pseudo-class weighs as much as a class in the specificity calculation, while a pseudo-element weighs as much as a tag. Soa:hover beats a, and .button:hover beats.button. This rule explains why a hover state almost always overrides the base style, without needing !important.
a { color: blue; } /* (0, 0, 1) */
a:hover { color: red; } /* (0, 1, 1): pseudo-class = weight of a class */
a::before { content: "→ "; } /* (0, 0, 2): pseudo-element = weight of a tag */.next-button::after {
content: "→";
margin-left: 8px;
transition: transform 0.2s ease;
display: inline-block;
}
.next-button:hover::after {
transform: translateX(4px);
}Pseudo-element pitfalls
::before and ::after never display without thecontent property (even an empty one: content: "";). They also don’t work on elements without content such as img or input. Finally, generated text can’t be selected: never put essential information in it.
Key takeaway
One : for a state or a position (:hover), two :: to target a part or generate content (::before). For the four historical pseudo-elements (::before, ::after,::first-line and ::first-letter), browsers still accept a single : for backward compatibility, but the current standard recommends the distinction.
Exercise
:hover effect (color change), then stripe an existing table with:nth-child(even).Exercise: keyboard focus
:focus-visible, then move through the page with the Tab key to check it.Exercise: form validation
:valid and:invalid, without JavaScript.Going further
h2heading on your page using ::beforeand the content property.