What Is CSS Pseudo-Class?

A CSS pseudo-class is a selector that selects element(s) based on some specific state the element is in (e.g. hover, focus, etc.). Pseudo-classes are added to a selector in the following way:

selector:pseudo-class {
  /* ... */

As you can see, a CSS pseudo-class is preceded by a single colon (:). This is to maintain a distinction from pseudo-elements which are preceded by double colon (::).

CSS has several pseudo-classes that can be categorized like so:

  • Linguistic pseudo-classes — allows styling of elements based on language or script direction (e.g. :dir and :lang);
  • Location pseudo-classes — allows styling of links and targeted elements within the current document (e.g. :visited, :target, etc.);
  • User action pseudo-classes — allows styling of elements based on some interaction by the user (e.g. :hover, :active, :focus, etc.);
  • Time-dimensional pseudo-classes — allows styling of elements when viewing something that has timing, such as WebVTT caption track (e.g. :current, :past, and :future);
  • Resource state pseudo-classes — allows styling of playable media, such as a video (e.g. :playing and :paused);
  • Input pseudo-classes — allows styling of form elements in different state before/after interaction (e.g. :autofill, :disabled, :checked, etc.);
  • Tree-structural pseudo-classes — allows styling of elements based on their location within the document tree (e.g. :root, :nth-child, :nth-of-type, etc.).

For example:

a:hover { text-decoration: none; }
a:active { text-decoration: line-through; }
input:focus { outline: none; }
input:disabled { cursor: not-allowed; }
li:first-child { margin-top: 0; }
li:last-child { margin-bottom: 10px; }

You can also combine pseudo-classes together. For example:

input:disabled:hover { cursor: not-allowed; }

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.