CSS Pseudo-classes and Pseudo-elements
CSS provides powerful styling tools: pseudo-classes and pseudo-elements. They help select elements based on their state or create styles for parts of elements.
Pseudo-classes
Pseudo-classes are selectors that allow you to select elements in a specific state (for example, on hover).
Pseudo-class Syntax
selector:pseudo-class {
/* styles */
}
Examples of Popular Pseudo-classes
:hover— on mouse hover.:focus— when element receives focus.:nth-child(n)— to select an element by its order number.:checked— for checked checkboxes or radio buttons.:not(selector)— selects elements that don't match the selector.
Pseudo-class Example
button:hover {
background-color: #007BFF;
color: white;
}
Usage Example:
Pseudo-classes allow you to create interactive elements, such as buttons that change appearance on interaction.
Pseudo-elements
Pseudo-elements allow you to style parts of elements (for example, the first letter or add text before an element).
Pseudo-element Syntax
selector::pseudo-element {
/* styles */
}
Examples of Popular Pseudo-elements
::before— inserts content before an element.::after— inserts content after an element.::first-letter— styles the first letter of text.::first-line— styles the first line of text.::placeholder— styles text inside input fields.
Pseudo-element Example
p::first-line {
font-weight: bold;
}
button::after {
content: " →";
}
Double Colon:
Modern CSS uses double colons (::) for pseudo-elements, but a single colon (:) is also allowed for backward compatibility
Comparison Table
| Feature | Pseudo-classes | Pseudo-elements |
|---|---|---|
| Syntax | :pseudo-class | ::pseudo-element |
| Focus | On element state | On part of element |
| Examples | :hover, :focus, :nth-child | ::before, ::after |
Browser Support:
Before using, make sure the required pseudo-class or pseudo-element is supported by all target browsers!