In this example, we will learn how to replace text in an element using CSS. We will be using visibility
and position
property along with the ::after
selector.
HTML
<div class="replace">
This is going to be replaced
</div>
CSS
.replace {
position: relative;
visibility: hidden;
}
.replace:after {
position: absolute;
content: "This is a new text. Hello!";
visibility: visible;
top: 0;
left: 0;
}
Output
Here, the visibility: hidden
hides the initial texts but that element takes up the space in the layout. So, we display the new texts after that element and make it position: absolute
to top: 0
and left: 0
so that it is displayed at the top of the initial text. The::after
selector inserts something after the content of the selected element and the content property specifies the content to be displayed after that element.
In this example, we learned how to replace text in an element using CSS. We used the visibility
and position
property and ::active
selector to hide the initial text and replace it with the new text.