Many people confuse or confuse CSS pseudo-classes with pseudo-elements. Today let’s look at the differences between the two. Before CSS3, there was no distinction between pseudo-elements and pseudo-classes, until CSS3 made the distinction.

Why pseudo-classes and pseudo-elements?

CSS introduces pseudo-classes and pseudo-elements to format information outside of the document tree. That is, pseudo-classes and pseudo-elements are used to modify parts of the document tree that are not there, such as the first letter in the first sentence or the first element in a list.

What is a pseudo-class?

A pseudoclass represents a state of a selected element, such as hover.

Classification of pseudo-classes

Stateful pseudo classes

Stateful pseudo-classes are selected based on the current state of the element, presenting one style when it enters one state and another style when it enters another state.

Typical stateful pseudo-classes are:

  • :link Indicates the link of the application that has not been accessed.
  • :hover applies to the element to which the mouse hovers.
  • :active Applies to the active element.
  • :visited applies to a link that has been visited. It is mutually exclusive with :link.
  • :focus applies to elements that have keyboard input focus.

Structural pseudoclass

CSS3 new selector, the use of DOM tree element filtering, through the mutual relationship of the document structure to match elements, can reduce the class and ID attribute definition, making the document structure more concise.

Examples of typical structural pseudo-classes are as follows:

  • Div :first-child Selects each div element that belongs to the first child of its parent element.
  • Div :last-child Selects each div element that belongs to the last child of its parent element.
  • Div: nth-Child (n) selects each div element that belongs to the NTH child of its parent.

What is a pseudo-element?

A pseudo-element represents a part of the selected element that looks like a separate element, such as ::before and ::after.

The difference between pseudo-classes and pseudo-elements

A pseudo-class manipulates an existing element in the document, whereas a pseudo-element creates and styles an element that is not in the document tree.