Difference Between Pseudo-Class and Pseudo-Element in CSS

css
Published on November 14, 2019

Use-Cases of this tutorial

  • Know the difference of pseudo-class vs pseudo-element.

Pseudo-class and pseudo-element are both CSS selectors, however pseudo-class represents a virtual CSS class, whereas pseudo-element represents a virtual HTML element.

Pseudo-Class

Pseudo-class selector helps in selecting different "states" of the same element. However pseudo-classes represent states based on information that lies outside the HTML source tree. Pseudo-classes are also used when it becomes difficult to select a particular state of the element using simple selectors (based on id, class, type and attribute).

CSS classes also represent various states of an element. Pseudo-class on the other hand represents an "artificial" CSS class of the element.

For example, consider an element in disabled state. The HTML tree does not hold information whether the element is in a disabled state or not — browser saves this information somewhere else. To select the element in this state, the :disabled pseudo-class is used.

Again consider that we need to select the first child of an element. The first child is present in the DOM tree, however selecting that would not be possible using simple CSS selectors. To do this, there is the :first-child pseudo-class selector.

Some of the pseudo-class selectors defined are :

  • Dynamic pseudo-classes that select elements based on features that are not saved in the DOM tree — :hover :visted :focus etc.
  • Language pseudo-classes that represent the same element, however in a different language — :lang
  • UI states that represent the same element, however in a different state — :disabled :checked etc
  • Structural pseudo-classes, where information is present in the DOM tree, however these are difficult to select via simple selectors — :first-child :nth-child() etc
  • Negation pseudo-class that represents an element not having a certain state — :not()

A pseudo-class' name is always prepended by a colon : character.

Pseudo-Element

Unlike pseudo-class that represents a virtual class of an element, a pseudo-element actually represents a new virtual element that represents a part of the element. A pseudo-element is not actually present in the DOM tree, but looks like it.

Some of the pseudo-element selectors defined are :

  • Pseudo-element representing the first line of the element — ::first-line
  • Pseudo-element representing generated content after or before an element's content — ::after ::before

A pseudo-element's name is always prepended by double colon :: characters.

In this Tutorial