CSSIntermediate
What are CSS pseudo-classes and pseudo-elements?
Pseudo-classes
Pseudo-classes target elements in a specific state, using a single colon :.
/* Mouse hover */
a:hover { color: blue; }
/* Focus */
input:focus { border-color: orange; }
/* First child */
li:first-child { font-weight: bold; }
/* Nth child */
tr:nth-child(even) { background: #f5f5f5; }
/* Form validation states */
input:valid { border-color: green; }
input:invalid { border-color: red; }
Common Pseudo-classes
| Pseudo-class | Description |
|---|---|
:hover |
When mouse hovers over the element |
:focus |
When element has focus |
:active |
When element is being clicked |
:visited |
Already-visited links |
:first-child |
First child of its parent |
:last-child |
Last child of its parent |
:nth-child(n) |
The nth child element |
:not(selector) |
Elements that don't match the selector |
Pseudo-elements
Pseudo-elements target or insert into specific parts of an element, using a double colon :: (CSS3 spec; single colon still accepted in older syntax).
/* Insert content before element */
.icon::before {
content: '★';
margin-right: 4px;
}
/* Insert content after element */
.required::after {
content: ' *';
color: red;
}
/* Style selected text */
p::selection {
background: yellow;
color: black;
}
/* First letter */
p::first-letter {
font-size: 2em;
}
Key Differences
| Pseudo-class | Pseudo-element | |
|---|---|---|
| Syntax | : single colon |
:: double colon |
| Purpose | Targets element states | Targets or creates specific parts of an element |
| Adds to DOM | ❌ | ✅ (::before / ::after) |
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
