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!
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.