The Difference Between Pseudo-classes and Pseudo-elements of CSS Properties

  • CSS Pseudo-classes are used to add special effects to some selectors.
  • CSS Pseudo-elements are used to add special effects to specific selectors.

Two points can be made clear, the first two are related to selectors, and the second is to add some “special effects”. Here, “special effects” mean that both describe things that other CSS can’t.

Kind of Pseudo-classes

Kind of Pseudo-elements

Difference between Pseudo-classes and Pseudo-elements

We use Pseudo-classes :first-child and Pseudo-elements ::first-letter for comparison.

first-child

p i:first-child {color: red}
<p>
<i>first</i>
<i>second</i>
</p>

Instead of Using Pseudo-classes, we can do it like this to achieve the above effect:

.first-child {color: red}
<p>
<i class=”first-child”>first</i>
<i>second</i>
</p>

That is, we add a class to the first child element, and then define the style of this class.

Next, we take a look at Pseudo-elements ::first-letter

first-letter

p:first-letter {color: red}
<p>I like coding.</p>

How can we achieve the effect without using Pseudo-elements?

.first-letter {color: red}
<p><span class=’first-letter’>I</span> like coding.</p>

We add a span to the first letter, and then define the style of this class.

The difference between the two is obvious: the effect of Pseudo-classes can be achieved by adding an actual class. In contrast, the effect of Pseudo-elements needs to be achieved by adding an actual element, which is the reason that they are called Pseudo-classes and Pseudo-elements.

Conclusion

The reason why Pseudo-elements and Pseudo-classes are easy to confuse is that both their effects and the way they are written are similar. In fact, in order to distinguish them, CSS3 has clearly stipulated that Pseudo-classes are represented by a colon, while Pseudo-elements are represented by two colons.

:Pseudo-classes
::Pseudo-elements