Pseudo-Classes & Pseudo-Elements
Pseudo-classes target elements based on their state or position in the DOM. Pseudo-elements target virtual sub-parts of elements. Together they eliminate the need for extra markup and JavaScript for many common UI patterns.
1 Pseudo-Classes
CSS — Pseudo-Classes
/* User interaction */
a:hover { color: #2563eb; }
button:active { transform: scale(0.97); }
input:focus { outline: 2px solid #6366f1; }
/* Form states */
input:valid { border-color: #22c55e; }
input:invalid { border-color: #ef4444; }
input:disabled{ opacity: 0.5; cursor: not-allowed; }
/* Structural */
li:first-child { font-weight: 700; }
li:last-child { border-bottom: none; }
li:nth-child(even) { background: #f8fafc; }
p:not(.special) { color: #374151; }
2 Pseudo-Elements
CSS — Pseudo-Elements
/* ::before and ::after inject content */
.badge::before {
content: "🔥 ";
}
/* Decorative underline */
h2::after {
content: "";
display: block;
height: 3px;
width: 40px;
background: #6366f1;
margin-top: 8px;
border-radius: 2px;
}
/* Custom scrollbar */
::-webkit-scrollbar { width: 8px; }
::-webkit-scrollbar-thumb { background: #6366f1; border-radius: 4px; }
/* First letter drop cap */
p::first-letter { font-size: 3em; float: left; line-height: 1; margin-right: 4px; }
3 Code Challenge
Challenge: Style a nav list so the active link has a colored underline using
::after pseudo-element. Use :nth-child(odd) to alternate table row backgrounds without JavaScript.