CSS:: Before and After

Photo by KOBU Agency on Unsplash

CSS:: Before and After

In CSS, there are different types of selectors available for selecting specific elements based on their type, state, etc.

Out of those selectors, there is a special type of selector which is used to select the specific part of the selected element to apply the styles. These selectors are termed as Pseudo element selectors.

Using this we can insert content without including it in the HTML document. There are many pseudo-elements such as ::first-letter,::first-line etc. but out of them the most commonly used ones are ::before and ::after.

::before

As the name suggests, this selector is used to insert content before the selected element. Syntax:

selector::before{
   //styling rules
}

Example:

h1::before{
   content:"Hello"
}

::after

We use after to insert content after the selected element. Syntax:

Selector::after{
//styling rules
}

Example:

h1::after{
content:"Hello"
}

Content Property

Both ::before and ::after have a content attribute that accepts a value that we can use to specify our content that we want to display before the original content. The acceptable values of content are:

String - We can just insert a string before the element. Ex: content:”Hello”

Image - Images can also be inserted before the element. Ex: content:url(‘/image.jpg’);

Nothing - Or we can just pass nothing , generally we use this for clearfixing.

Applications

Let’s see some applications of these selectors to gain in depth understanding of these selectors.

  • Adding Emojis to your web page

Since we already know that emojis can be represented using their Unicode characters therefore we can use the Unicode value as a string to set the content property. Example: HTML:

<h2> Heading </h2>

CSS:

 h2::before{
content:'\1F600';
}

OUTPUT:

image.png

  • Elegant Headings

We can add more elegance to the headings just by using these two selectors. Example: HTML:

<h1>Elegant Heading </h1>

CSS:

h1 {
  display: grid;
  grid-template-columns: minmax(50px, 1fr) auto minmax(50px, 1fr);
  align-items: center;
  text-align: center;
  gap: 40px;
}

h1::before, h1::after {
  content: '';
  border-top: 6px double;
}

Output:

image.png

This inserts border as pseudo elements before and after the heading text. And since we already used the border-top property , therefore we are getting only the top border. We have also set the content property to empty string because we don’t want any content out there, all we need is just the border.

Other examples:

Just like these two examples, there are a lot of things that we can achieve using the before and after selectors.

Some of the cool applications of before and after are:

Tip: Css-tricks is the coolest website I have come across for understanding css. They have some great articles on before and after. Be sure to check it out.