Guide to What are pseudo-classes and pseudo-elements?

Guide to What are pseudo-classes and pseudo-elements?

Let's first understand what are pseudo-classes

Pseudo-classes

  • Pseudo-classes are used to define the special state of an element.
  • We can add to an element with the help of a selector to give effect to the existing element.

E.g. :hover is used to give effects to element when we take a mouse on an element.

Let's understand some of the pseudo-classes with example.

:hover

When a user moves the mouse pointer on an element we can add special effects using : hover pseudo-class.

Let's understand this with an example.

You can see in the above example whenever we move the mouse pointer to the div element background color changes. We can apply :hover pseudo-class on any element.

I have changed only the background property. But you can try with different properties.

:first-child

:first-child pseudo-class is used to select specified selector only and only if it is the first child of its parent.

You will get a clear understanding with examples.

In the above example you can see we selected only the first child. Let's try to read syntax of this example.

div p:first-child{
  color: skyblue;
}

The above syntax says that select the first child of div(division) which is p(paragraph)

:last-child

:last-child works the same as :first-child but instead of selecting first-child, it selects the last child of the element specified.

:nth-child(n)

With help we :nth-child we can select any child of the parent.

n can be a value (odd or even) or a formula (an + b).

element:nth-child( even / odd / an+b )

There are many pseudo-classes we can't explore each of them. You can refer to below link to find out all pseudo-classes.

Link

Pseudo-elements

pseudo-element is used to style certain parts of an element.

There are 2 important pseudo-element we need to understand. You can find the rest of the pseudo-elements on LINK

  • We use :: with pseudo-element and : with pseudo-classes

::before

  • The ::before pseudo-element is used to insert some content before the content of a selected element.

  • It is often used to add cosmetic content to an element with the content property. It is inline by default.

  • We can use ::before for Gradient overlays.

::after

  • The ::after pseudo-element is used to insert some content after the content of a selected element.

Summary

  • Most times you will see content: "" found in the ::before and ::after pseudo-elements. But the content property has many useful applications.

  • if you want to add an icon before every link on your site, it would be much easier to add it through the content property than to add it to every element in the HTML document.

Did you find this article valuable?

Support kedarBlog by becoming a sponsor. Any amount is appreciated!