Introduction
Pseudo-classes and pseudo-elements are highly powerful features in CSS. They allow you to style elements based on state, position, or specific parts without adding extra HTML. They are essential for navigation menus, buttons, forms, and modern interactive designs.
In this chapter, you will learn:
- What pseudo-classes are and how they work
- Common state-based selectors (:hover, :focus, :active)
- Structural selectors like :nth-child
- Pseudo-elements (::before, ::after) and their power
- Real-world UI patterns and best practices
Pseudo-Classes (State-Based)
A pseudo-class selects an element based on its state or condition.
/* Syntax */
selector:pseudo-class {
property: value;
}Common User Action States
| Pseudo-Class | Description |
|---|---|
:hover | User mouse over |
:active | While clicking (button press) |
:focus | Input focused (keyboard/click) |
:visited | Visited link |
Examples
button:hover {
background-color: #0056b3;
}
input:focus {
border-color: #007bff;
outline: none;
}Structural Pseudo-Classes
Select elements based on their position in the DOM.
/* First element inside parent */
li:first-child { font-weight: bold; }
/* Last element */
li:last-child { color: red; }
/* Specific position or pattern (Even/Odd) */
tr:nth-child(even) { background-color: #f9f9f9; }Form-Based Pseudo-Classes
Useful for styling form states.
input:checked { accent-color: green; }
input:disabled { background-color: #f1f1f1; }
input:required { border-left: 3px solid red; }Pseudo-Elements (::)
Pseudo-elements style specific parts of an element. Note the double colon (::).
::before and ::after
Insert content before or after an element without modifying HTML.
/* Add star before heading */
h2::before {
content: "★ ";
color: gold;
}
/* Custom list bullet */
li::before {
content: "✔";
margin-right: 8px;
color: green;
}Text Selection
Customize the color of highlighted text.
::selection {
background-color: #007bff;
color: white;
}Common Beginner Mistakes & Best Practices
Common Mistakes
- Forgetting
contentproperty in ::before/::after - Confusing simple colon (:) with double colon (::)
- Overusing pseudo-elements for unrelated content
Best Practices
- Use pseudo-classes for interactivity (hover, focus)
- Use pseudo-elements for decoration (icons, dividers)
- Keep selectors simple for performance
Chapter Summary
In this chapter, you learned:
- Pseudo-classes (:) select based on state (hover, focus, nth-child).
- Pseudo-elements (::) style parts of an element (before, after, first-line).
- Real-world patterns like zebra striping, custom bullets, and interactive buttons.
You now have the foundation to build interactive, modern UI effects using pure CSS.