Open In App

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:

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.

Approach:

<p class="toBeReplaced">Old Text</p>
.toBeReplaced {
visibility: hidden;
position: relative;
}
.toBeReplaced:after {
visibility: visible;
position: absolute;
top: 0;
left: 0;
content: "This text replaces the original.";
}

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






<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:

Using Pseudo-elements & CSS Visibility

This approach utilizes pseudo-elements and CSS visibility to achieve text replacement. The original text is hidden using a hidden span, and the replacement text is added using the :after’ pseudo-element.

Approach:

.toBeReplaced span {
display: none;
}
.toBeReplaced:after {
content: "This text replaces the original.";
}

Example: Implementation to replace text using aabove approach.




<html>
 
<head>
    <title>
        Using Pseudo-elements & CSS Visibility
    </title>
    <style>
        .toBeReplaced span {
            display: none;
        }
 
        .toBeReplaced:after {
            content: "This text replaces the original.";
        }
    </style>
</head>
 
<body>
    <p class="toBeReplaced"><span>Old Text</span></p>
</body>
 
</html>

Output:

CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.


Article Tags :