Hello, World! ๐๐ป
In this article, We are going to see what is ::before
and ::after
pseudo-element and how to use them in CSS.
So, Are you guys excited? Okay, then fasten your seatbelts and Let's Gooooo. ๐ค๐ป
Okay so before understanding the ::before
and ::after
pseudo-elements, Let's go through the definition of pseudo-elements.
What is pseudo-element?
A pseudo-element is a keyword added to a selector that lets you style a specific part of the selected element.
It means it will allow you to add some extra styling for that particular element.
Okay, now as we are clear with the pseudo-elements, Let's move to ::before
and ::after
pseudo-elements.
What is ::before
and ::after
pseudo-element?
::before
and ::after
pseudo-elements are elements that allow us to add some extra content before/after our elements.
Let's understand this by some examples.
Before jumping to the examples, there are some important points about these elements which we should know.
These elements will only work with block-level elements.
The most important thing about these elements is that they must have a
content
property in them.
Now, Let's jump to examples.
Example of ::before
Let's assume that you have a list of students and you have to show their name but you also need to show some abbreviations with the name (which are not available in the data you have)
At that time you can use ::before
pseudo-element
<style>
.male-student::before {
content: 'Mr. ';
}
.female-student::before {
content: 'Ms. ';
}
</style>
<div>
<p class="male-student">Harry Potter</p>
<p class="female-student">Hermione Granger</p>
</div>
<!--
Output:
Mr. Harry Potter
Ms. Hermione Granger
-->
Example of ::after
Same as the previous example, now you need to display the age of the student but you have only digits of age in your data.
In this case, you can use ::after
pseudo-element
<style>
.age::after {
content: ' years old.'
}
</style>
<div>
<p class="age">22</p>
<p class="age">21</p>
</div>
<!--
Output:
22 years old.
21 years old.
-->
Pretty simple, isn't it?
So, now you all know how to use ::before
and ::after
pseudo-elements, right?
Wrapping Up
Pseudo-elements are a very good feature provided by CSS and there are many other pseudo-elements available in CSS. These pseudo-elements can help us in very things while styling ou elements and can save us a lot of time.
Here are some of the links on which you can get more about CSS Pseudo-elements