Topic 33 of 62
Pseudo-Classes
Overview
HTML tags are static, but the user's interaction with the webpage is deeply dynamic. Pseudo-classes allow CSS to 'listen' for these temporary states (like hovering over a button or clicking a link) and apply styles conditionally, all without writing a single line of JavaScript. They act as automated state machines built directly into the CSS engine.
Syntax
css
/* 1. Interaction States */
.btn:hover { background: blue; } /* User's mouse is over the element */
.btn:active { transform: scale(0.9); } /* The exact moment the user clicks */
.input:focus { border: 2px solid gold; } /* User is typing inside the input */
/* 2. Structural States (DOM Navigation) */
/* Target the very first <li> in a list */
ul li:first-child { border-top: none; }
/* Target every even-numbered row (Stripe effect!) */
tr:nth-child(even) { background: #eee; }
/* Target the 3rd <li> specifically */
li:nth-child(3) { color: red; }
/* 3. Form Validation States */
input:invalid { border-color: red; }
input:disabled { opacity: 0.5; }Common Pitfalls
- The 'LoVe HAte' rule for styling links. If you write your pseudo-classes in the wrong order, they will override each other and break. You must declare them exactly in this order:
:link,:visited,:hover,:active(LVHA). - Confusing
:nth-childwith:nth-of-type.p:nth-child(2)selects the paragraph ONLY if it is literally the second child in its parent div. If there is an<h1>above it, the paragraph is the second child. But if there are two<h1>s above it, it fails.p:nth-of-type(2)ignores all other elements and strictly finds the second paragraph.
Interview Questions
Q:
What is the accessibility issue with using
:hover to reveal critical information (like a dropdown menu)?A:
Mobile touch screens do not have a 'hover' state. A user's finger is either touching the screen (:active) or not. If you hide critical UI behind a pure :hover state, mobile users can never access it.
Real-World Example
Using structural pseudo-classes to build a responsive CSS Grid without manual classes.
example
css
.grid { display: grid; gap: 10px; }
/*
If a card is the very first child, make it span the entire row!
Every subsequent child will just act normally.
*/
.grid .card:first-child {
grid-column: 1 / -1;
font-size: 1.5rem;
}Check Your Knowledge
Test your understanding of Pseudo-Classes with these quick questions.