From :hover to :nth-child — CSS Pseudo-classes

In CSS, sometimes we need styles that change based on a special state or condition of an element. That’s where pseudo-classes come in. They’re like CSS’s way of saying, “When this happens, use this style.

You see these pseudo-classes very often. When you hover over a link and it changes color; that’s: hover in action. When you click a button and it stays highlighted; that’s: active.

Pseudo-classes are not new elements. They’re “hooks” into existing ones, triggered by things like user interaction, DOM position, or input validity.

Practical Pseudo-class Examples

Pseudo-classes have a wide range of uses. Some of the most common include:

  • :hover – Styles an element when the mouse is over it.
Here, button changes color when you hover the mouse.
(click on the image to open in a new tab)
  • :focus – Activates when an element is focused (e.g., clicking into a form field).
Input gets an orange outline when you click or tab into it.
(click on the image to open in a new tab)
  • :active – This pseudo-class lets you target an elment’s active state.
Here, button turns red while you’re holding the mouse button down.
(click on the image to open in a new tab)
  • :visited – It lets you style a previously visited link.
Here, link turns purple after you click it.
(click on the image to open in a new tab)
  • :nth-child(n) – Targets specific items in a list or grid based on order.
:nth-child(2) makes the second item in the list green.
(click on the image to open in a new tab)
  • :first-child – It selects the element if it’s the first child of its parent.
:first-child here makes the first list item bold.
(click on the image to open in a new tab)
  • :last-child: This pseudo-class represents the last element among a group of sibling elements.
Here, :last-child makes the last list item blue

  • :disabled – Styles Form elements which are not interactive.
:disabled here styles the disabled input with a grey background.
(click on the image to open in a new tab)

  • :checked – This selector represents any input or option that is checked.
Adds a green glow to a checked checkbox.
(click on the image to open in a new tab)
  • :required – It selects and style form elements with a “required” attribute.
Here,:required outlines the required email field in red.
(click on the image to open in a new tab)

For a complete list of pseudo-classes you can check the MDN website.

Why They’re Powerful

Without pseudo-classes, you’d need JavaScript to detect many of these conditions. With them, CSS can do it instantly and efficiently. They’re also chainable. You can combine them for very specific styling.

When to Use Them

Use pseudo-classes when you want styles to respond to changes without manually adding any JavaScript.

In short, pseudo-classes are CSS’s built-in event listeners, ideal for dynamic designs.

Although my blog doesn’t support comments, feel free to reply via email or X.