Lesson 19 of 50
cssPseudo‑Classes & Pseudo‑Elements
12 mins
Course progress38%
What you'll learn
Keep these ideas in mind as you work through the lesson.
Lesson 19 of 50
css12 mins
Keep these ideas in mind as you work through the lesson.
Pseudo‑classes address states of an element (e.g., :hover, :focus, :nth-child). Pseudo‑elements generate virtual child elements (::before, ::after, ::first-line, ::first-letter).
:hover – mouse pointer over the element.:focus – element receives keyboard focus.:focus-visible – focus only when the user needs to see it (e.g., keyboard navigation).:nth-child(n) – targets the n‑th child (supports odd, even, 2n+1).:not(selector) – selects everything except the listed selector.:has(selector) – relational selector (parent‑level selector) – currently in Chrome 105+ and Safari 15.4+.::before & ::after – create a box before or after the element’s content. Require a content property (even an empty string). Great for decorative icons or overlays.::first-line – style only the first formatted line of a block.::first-letter – typographic drop‑caps.::after.btn {
position:relative; overflow:hidden; padding:0.8rem 1.5rem; border:none;
background:#0066cc; color:#fff; cursor:pointer;
}
.btn::after {
content:"";
position:absolute; inset:0; background:linear-gradient(45deg,rgba(255,255,255,.3),transparent);
transform:scaleX(0);
transform-origin:left;
transition:transform .4s ease;
}
.btn:hover::after { transform:scaleX(1); }
The pseudo‑element expands on hover, creating a ripple effect without extra markup.
:has() For Accessible Form Validationinput:invalid + .error {
display:block;
}
/* Show error only when the parent .field contains an invalid input */
.field:has(input:invalid) .label {
color:#c00;
}
No JavaScript needed to style the label when the sibling input is invalid.
If you find yourself writing ul.navigation > li > a:hover::before, consider adding a utility class instead (.nav-link:hover::before). Utility classes keep the cascade manageable.