Skip to main content
Practice Problems

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

css
selector:pseudo-class { /* styles */ }
  • :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

css
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

css
selector::pseudo-element { /* styles */ }
  • ::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

css
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

FeaturePseudo-classesPseudo-elements
Syntax:pseudo-class::pseudo-element
FocusOn element stateOn 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems