When inspecting the HTML code in the dev tools you might have come across the ::before and ::after in the code. Those are called pseudo elements.
What are pseudo elements
Pseudo element is a keyword added to the selector that allows us to style the specific parts of the selected element. These help us not only to keep the HTML clean from decorative elements as well helps us to customize text in the selected element.
Initially the pseudo elements were represented using single colon convention (i.e. :after
). In CSS3 the single colon convention was replaced to double colon convention (i.e.::after
). This was introduced to differentiate between pseudo-elements and pseudo-classes.
Some of the pseudo elements are:
::after
::before
::first-letter
::first-line
::selection
In this post let us look at the two most commonly used pseudo elements ::before
and ::after
.
::before
and ::after
These are often used to add decorative content to the selected element. These pseudo elements does not appear in the DOM and are created using CSS. These create a child inside the element only if the content property is defined. The content property is used to add the desired content. By default the content property is set to none. The content property can be a string, even an empty string or an image URL. These elements are inline by default and can be modified according to your needs.
Lets look at the example to add quotation marks. You might say we can add this directly in the HTML, but if we do so we wont be able to customize the quotation marks.
One thing to look out when using these pseudo elements is that we wont be able to select the content added by these.
::before
pseudo element
The ::before
pseudo element creates an element before the content of the selected element.
Lets say you want to add a custom list style to the lists. We can do that by using the ::before
pseudo selector.
In the above example we have used the Orange Diamond emoji as the content to the ::before
pseudo selector.
::after
pseudo element
Same as the ::before
selector, only difference is that the element is added after the content of the selected element.
Lets use this selector to add a pdf icon to the end of the link.
In this example we have set the font family to 'Font Awesome 5 Free' and have used the Unicode as the content to the selector.
Check the below demos by Will Boyd, this will give you some ideas on how to use these pseudo elements.
Demos of using pseudo elements to create Decorative headings
This is just a basic explanation to get to know the pseudo elements ::before
and ::after
. Now you can start using these to add some amazing designs to your site.
If you have found any mistake in this post please comment and be free to give any suggestion you want.