How to use :after Pseudo-element In CSS

The ‘: after’ pseudo-element in CSS is utilized to insert additional content after the selected element, enabling techniques such as text replacement or the addition of decorative elements.

Approach:

  • To start with, we wrap the text and assign it to a class. This method requires very little markup.
<p class="toBeReplaced">Old Text</p>
  • The text “Old Text” needs to be hidden first and a new text has to be positioned exactly where the old text was. To do so, we change the visibility of this text using CSS to hidden first.
.toBeReplaced {
visibility: hidden;
position: relative;
}
  • Then we add a new text at the exact same position, using the pseudo elements and corresponding explicit positioning.
.toBeReplaced:after {
visibility: visible;
position: absolute;
top: 0;
left: 0;
content: "This text replaces the original.";
}
  • Note that after is the pseudo element in use here. We use the visibility modifier once again to show the new text. The content attribute contains the new text.

Example: Implementation to replace text using :after Pseudo-element

html




<html>
 
<head>
    <title>
        Using :after Pseudo-element
    </title>
    <style>
        .toBeReplaced {
            visibility: hidden;
            position: relative;
        }
 
        .toBeReplaced:after {
            visibility: visible;
            position: absolute;
            top: 0;
            left: 0;
            content: "This text replaces the original.";
        }
    </style>
</head>
 
<body>
    <p class="toBeReplaced">Old Text</p>
</body>
 
</html>


Output:

How to replace text with CSS?

Replacing a text is mostly worked out on the server side. But in some circumstances, where we don’t have control over the server, or we are working under restrictions, replacing text using CSS may be a choice. The multiple approaches to do so are as:

Table of Content

  • Using :after Pseudo-element
  • Using Pseudo-elements & CSS Visibility

Similar Reads

Using :after Pseudo-element

The ‘: after’ pseudo-element in CSS is utilized to insert additional content after the selected element, enabling techniques such as text replacement or the addition of decorative elements....

Using Pseudo-elements & CSS Visibility

...