Phase 4 — Responsive & Modern
#16 Pseudo-elements and pseudo-classes
::before, ::after, :hover, :nth-child
Pseudo-elements
Pseudo-elements create virtual elements that you can style without adding HTML. They use double colons (::):
::before and ::after
/* Add decorative content before an element */
.quote::before {
content: "\201C"; /* Opening quote mark */
font-size: 3rem;
color: #3b82f6;
line-height: 1;
}
/* Add required asterisk after labels */
.required::after {
content: " *";
color: #ef4444;
}
/* Decorative line under heading */
h2::after {
content: "";
display: block;
width: 60px;
height: 3px;
background: #3b82f6;
margin-top: 8px;
}Other pseudo-elements
More pseudo-elements
/* Style first line of text */
p::first-line {
font-weight: bold;
color: #1a1a2e;
}
/* Style first letter */
p::first-letter {
font-size: 3rem;
float: left;
margin-right: 8px;
color: #3b82f6;
}
/* Style selected text */
::selection {
background: #3b82f6;
color: white;
}
/* Style placeholder text */
input::placeholder {
color: #9b9baa;
font-style: italic;
}Pseudo-classes
State pseudo-classes
/* Hover and active states */
a:hover { color: #3b82f6; }
.button:active { transform: scale(0.98); }
/* Focus states */
input:focus {
border-color: #3b82f6;
outline: 2px solid #3b82f6;
outline-offset: 2px;
}
/* Form states */
input:required { border-left: 3px solid #3b82f6; }
input:valid { border-color: #10b981; }
input:invalid { border-color: #ef4444; }
input:disabled { opacity: 0.5; }Structural pseudo-classes
Structural selectors
/* First and last child */
li:first-child { font-weight: bold; }
li:last-child { border-bottom: none; }
/* nth-child patterns */
tr:nth-child(even) { background: #f5f5f5; } /* Zebra rows */
tr:nth-child(odd) { background: white; }
.grid > :nth-child(3n) { grid-column: span 2; } /* Every 3rd */
/* Not selector */
p:not(:last-child) { margin-bottom: 1em; }Your turn
Try the pseudo-element commands below:
terminal — browser