What's the Difference Between CSS Pseudo-Element and Pseudo-Class?

CSS pseudo-classes and pseudo-elements have three main differences in terms of:

  1. Syntax;
  2. Functionality;
  3. Application.

Syntax

Pseudo-classes and pseudo-elements have a different syntax:

selector:pseudo-class { }

selector::pseudo-element { }

Pseudo-classes are preceded by a single colon (:) while pseudo-elements are preceded by a double colon (::).

Please note that this syntactical distinction was not present in older versions of the W3C spec. Therefore, most browsers support the use of single colon (:) and double colon (::) for pseudo-elements.

Functionality

Pseudo-classes allow styling based on some special state of the selected element(s) while pseudo-elements allow styling of a specific part of the selected element(s). For example:

<ul>
    <li>foo</li>
    <li>bar</li>
</ul>
li::selection { background-color: pink; }

li:hover { text-decoration: line-through; }

This does the following:

  • The ::selection pseudo-element applies styles to the li element that has been highlighted by the user;
  • The :hover pseudo-class matches when the user hovers over the li element with the cursor (mouse pointer).

Application

There can only be one pseudo-element per selector. However, the same is not true for pseudo-classes as they can be combined to select a specific state of the element. For example:

<label for="foo">Foo</label>
<input id="foo" type="text" required />
label[for]::after { content: ': '; }

input:invalid:focus:hover { outline-color: red; }

This does the following:

  • ::after creates a pseudo-element as the last child of the label element to add ": " to its content;
  • The :invalid:focus:hover pseudo-class matches when the input field is invalid, has focus and the user hovers over the element.

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

p:first-of-type::first-line { font-weight: bold; }

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.