Pseudo Elements in CSS

Pseudo Elements CSS

The pseudo-elements are used for styling a specific part of an element. It is like if we want to style only the first letter for some element, or the first line of some element, or insert some content before or after content, or even if we only want to style the selection from the user, we can make use of the pseudo-elements.

Remember that when we want to style for some particular state of some element, we wrote the selector name, and then we used the single colon, and then wrote the pseudo-class. But when we are styling for some particular part of the element, we are going to write the selector name first, then a double colon, and then the pseudo-element.

Below given are some of the pseudo-elements –

  • ::first-letter – as the name says, this element is used to specify the first letter of some element, so that we can style it as per our requirement.
  • ::first-line – This element is going to specify the first line of some element, so as tho be able to style it
  • ::before – this element is used when we want to add some content before the element
  • ::after – this element is used when we want to add some content after the element
  • ::selection – we use it when we want to do something with the selection of the text. It is like we are styling the text, which is selected by the user.

Remember that when we were having a look at pseudo-classes, we used one colon, something like this – selector:classname. But this time, for using the pseudo-elements, we are going to make use of double colons, which means that we are going to do something like this – selector::elementname.

So, now it is easy to identify what are we really using. Is it a pseudo-class or an element that we are making use of. Let’s have a small example, so as to understand the things-

As you can see here, we have a paragraph, and 2 div blocks over here. We are going to do different things with the specific parts of the elements. Let’s have a look at what is in our CSS file –

So, for the specific parts of the elements, we have done different things, like when we select some text from the div element, the background color is brown(instead of the standard blue color), and the color of the text is white. We have also used the before and after things, to add some texts like Hello, which is added just before the content of div, and Bye, which will be added just after the content of div. Also, we have done different things with the first line and first letter of some elements. Let’s have a look at the output now –

As you can see in the output, the things that we wanted to do, are done now. You can use the pseudo-elements whenever we require them.