In CSS, pseudo-classes and pseudo-elements are used to style elements based on special states or parts of elements that cannot be selected directly using regular selectors.
🎯 1. Pseudo-Classes (:)
A pseudo-class targets an element based on its state — for example, when a user hovers over a button or when a link has been visited.
🧩 Common Examples:
/* When a user hovers over a button */
button:hover {
background-color: blue;
color: white;
}
/* When an input field is focused */
input:focus {
border-color: green;
}
/* Style a visited link */
a:visited {
color: purple;
}
/* Style every even table row */
tr:nth-child(even) {
background-color: #f2f2f2;
}
💡 In short:
Pseudo-classes describe a state of an element.
🧱 2. Pseudo-Elements (::)
A pseudo-element allows you to style specific parts of an element — like the first letter, first line, or to insert content before/after it.
🧩 Common Examples:
/* Style the first letter of a paragraph */
p::first-letter {
font-size: 2em;
color: red;
}
/* Style the first line of text */
p::first-line {
font-weight: bold;
}
/* Insert content before an element */
h1::before {
content: "🔥 ";
}
/* Insert content after an element */
h1::after {
content: " ✨";
}
💡 In short:
Pseudo-elements let you style specific parts of elements or add virtual content.
🧩 Difference Summary
| Feature | Pseudo-Class | Pseudo-Element |
|---|---|---|
| Syntax | : |
:: |
| Targets | Element state | Element part/content |
| Example | :hover, :focus, :nth-child() |
::before, ::after, ::first-letter |
✅ Example combining both:
button:hover::after {
content: " 👋";
}
🪄 When the user hovers over the button, a waving emoji appears after its text — showing both concepts in action.