CSS pseudo-classes are keywords added to selectors that style elements based on dynamic user states, structural DOM positions, or form input validation checks.
Pseudo-classes begin with a single colon (:):
/* User State Pseudo-Classes */
button:hover { background-color: #1d4ed8; }
button:active { transform: scale(0.98); }
input:focus-visible { outline: 2px solid #38bdf8; }
/* Structural Pseudo-Classes */
li:first-child { font-weight: bold; }
li:last-child { margin-bottom: 0; }
tr:nth-child(even) { background-color: #1e293b; }
/* Form Check Pseudo-Classes */
input:checked + label { color: #34d399; }
input:invalid { border-color: #ef4444; }
Primary categories:
:hover, :active, :focus, :focus-visible.:first-child, :last-child, :nth-child(n), :not(selector).:checked, :disabled, :required, :valid, :invalid.flowchart LR
A["Normal State (button)"] -->|Mouse Over| B[":hover"]
B -->|Mouse Down| C[":active"]
A -->|Tab Key Focus| D[":focus-visible"]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CSS Pseudo-Classes Example</title>
<style>
.list-group {
list-style: none;
padding: 0;
max-width: 400px;
}
.list-group li {
padding: 12px;
background-color: #1e293b;
border-bottom: 1px solid #334155;
}
.list-group li:first-child {
border-top-left-radius: 8px;
border-top-right-radius: 8px;
}
.list-group li:last-child {
border-bottom-left-radius: 8px;
border-bottom-right-radius: 8px;
border-bottom: none;
}
.list-group li:hover {
background-color: #334155;
}
</style>
</head>
<body style="background-color: #0f172a; color: #f8fafc; font-family: system-ui, sans-serif; padding: 2rem;">
<h2>List Group with Structural Pseudo-Classes</h2>
<ul class="list-group">
<li>Item One (Rounded Top)</li>
<li>Item Two</li>
<li>Item Three (Rounded Bottom)</li>
</ul>
</body>
</html>
:nth-child(even) for alternating table row colors: Makes scanning wide data grids much easier.:not() to exclude elements from rules: Write li:not(:last-child) { margin-bottom: 10px; } to add spacing between all list items except the final one.:hover state changes with CSS transitions: Add smooth transitions for interactive states.Create a CSS rule using :not(:last-child) that applies a margin-right: 1rem; to elements!
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With
Experiment with the code from this lesson in our interactive playground.