:: before & ::after in CSS Explained

Β·

3 min read

:: before & ::after in CSS Explained

Hey ReadersπŸ‘‹

Today we are going to learn about ::before and ::after pseudo elements.

Often considered as one of those topics in CSS that scares almost every beginners. The main cause behind this is the lack of good examples. As a beginner I was too scared of these pseudo classes and it was like a nightmare to me. I curated few simple and easy to understand example in this article so that anyone can understand it better. Lets get started.

What actually are ::before and ::after ?

  • In CSS, these are known as pseudo elements.

A pseudo-element is used to style specified parts of an element.

For example, it can be used to:

  • Style the first letter, or line, of an element

  • Insert content before, or after, the content of an element

Both the ::before and ::after pseudo-elements create a child element inside an element only if you define a content property.

 .my-element::before {
    content: "";
}

.my-element::after {
    content: "";
}

The content can be any string β€”even an empty one but be mindful that anything other than an empty string will likely be announced by a screen reader.

Once a ::before or ::after element has been created, you can style it however you want with no limits.

Lets know more about each of the two by looking at some examples.

::before

  • The ::before pseudo-element can be used to insert some content before the content of an element.
  • It is inline by default.

EXAMPLE : Check the output below πŸ‘‡

::after

  • The ::after pseudo-element can be used to insert some content after the content of an element.
  • It is inline by default.

EXAMPLE : Check the output below πŸ‘‡

  • Let's see some more examples to understand the use of ::before and ::after pseudo class better.

Example 1: Adding quotation marks

  • One simple example of using ::before pseudo-elements is to provide quotation marks. Here we use both ::before and ::after to insert quotation characters.

HTML πŸ‘‡

<p>
<q>Some quotes</q>, he said, <q>are better than none.</q>
</p>

CSS πŸ‘‡

q::before {
  content: "Β«";
  color: blue;
}

q::after {
  content: "Β»";
  color: red;
}

Check the Output Below πŸ‘‡

Example 2 : Gradient Borders

HTMLπŸ‘‡

<div class = "gradient-border"</div>

CSS πŸ‘‡

.gradient-border {
width: 500px; 
height: 300px;
margin: 10px;
background-color: #111;
position: relative;
}

.gradient-border::before{
content: " " ;
position: absolute;
z-index: -1;
top: -20px;
left: -20px;
bottom: -20px;
right:-20px;
background-image: linear-gradient(#ff7a00, #ff1a00);
}

Check the Output below πŸ‘‡

The End

I hope you found this article valuable. If yes do let me know in the comments 😊

Also if you got any questions feel free to ping me on Twitter

You can now extend your support by buying me a Coffee.πŸ˜ŠπŸ‘‡

Did you find this article valuable?

Support Insha's Blog by becoming a sponsor. Any amount is appreciated!

Β