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:
- Pseudo-class selector
- Pseudo-element selector
As already mentioned, pseudo-classes can be used to define an element at a particular state. A great example is hover.
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,
We can style the link for each states using
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
: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
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 are used style a part of an element. For example,
::first-line pseudo-elements are used to style first letter and line respectively.
In the above code, we used
::first-line pseudo-elements to style the first letter and line accordingly.
One of the best thing about pseudo-elements is the
::after pseudo-elements which can be used to insert content before or after an element.
For that, we have to use the
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.