With pseudo-selectors, we are not selecting an entire element. Instead, we are targeting an element when it is at a particular state or only a portion of that element.

When we target an element at particular state, it is called a pseudo-class. The best example would be the :hover pseudo class which targets an element when mouse hovers over it.

We can also target a part of an element using pseudo-elements. The best example would be the ::first-letter pseudo-element you can use to target the first letter of a text.

Watch video instead:

So, there are two types of pseudo-selectors:

  1. Pseudo-class selector
  2. Pseudo-element selector

Pseudo-class selectors

As already mentioned, pseudo-classes can be used to define an element at a particular state. A great example is hover.

codepen example

In the above example, I have used the :hover pseudo class to change background color to dark blue.

We can also use pseudo-classes to style html links in different states. Normal html links have 3 states,

  1. unvisted
  2. visited
  3. active

We can style the link for each states using :link, :visited, and :active pseudo-class.

codepen example

In the example above, you can see that the default color of the link is green. Try pressing the link and the color will become hotpink until it is released where it becomes red.

You can see in the CSS, I used :link, :visited, and :active pseudo-classes to style it. Once the link is visited, it will always be in the visited state until you delete the history.

Now let's have some fun and create a basic tooltip. For this, we will use the :hover pseudo-class.

codepen example

Basically we have 2 paragraphs, one of which is set to display: none. When we hover over the other one, display value is changed back. With better styling, we can create a much better tooltip but I just wanted to go through the possibilities.

This is in no way a complete guide to pseudo-classes, I recommend checkign out this mdn article.

Pseudo-element selectors

Pseudo-element selectors are used style a part of an element. For example, ::first-letter and ::first-line pseudo-elements are used to style first letter and line respectively.

codepen example

In the above code, we used ::first-letter and ::first-line pseudo-elements to style the first letter and line accordingly.

One of the best thing about pseudo-elements is the ::before and ::after pseudo-elements which can be used to insert content before or after an element.

For that, we have to use the content property.

codepen example

open-quote and close-quote transforms to open and close quote symbols. Try injecting "hello" text or anything and play around.

Here is an mdn article I think you will find useful.

Written by Aravind Sanjeev, an India-based blogger and web developer. Read all his posts. You can also find him on twitter.